我有一个has_one关联,它反映在另一个关联的对象上。我有一个项目,它有很多ProjectUsers,将项目和用户联系在一起。其中一个ProjectUsers是权威的。问题是has_one和has_many在project_users上使用相同的外键。以下是这些模型的基本思想。
class Project < ActiveRecord::Base
has_many :project_users, :class_name => 'ProjectUser', :foreign_key => 'project_id'
has_one :authoritative_user, :class_name => 'ProjectUser', :foreign_key => 'project_id', :conditions => {:authoritative => true}
end
class ProjectUser < ActiveRecord::Base
belongs_to :project
belongs_to :user
# has a boolean column 'authoritative'
end我想要做的是调用类似这样的东西。
project = Project.new
project_user = ProjectUser.new
project.project_users << project_user
project.authoritative_user = project_user
other_project_user = ProjectUser.new
project.project_users << other_project_user
project.authoriative_user = other_project_user其中,authoritative_user=会将项目用户更新为将authoritative设置为true,并将前一个权威用户的authoritative设置为false。我遇到的另一个问题是,我第二次在项目上设置authoritative_user时,前一个ProjectUser上的project_id被设置为零,因此它通过项目的project_users不再关联。
我不确定是我做得完全错了,还是我错过了什么。
发布于 2010-09-25 05:44:06
class Project < ActiveRecord::Base
has_many :project_users
has_many :users, :through => :project_users
belongs_to :authoritative_project_user, :class_name => 'ProjectUser'
has_one :authoritative_user, :through :authoritative_project_user
end
class ProjectUser < ActiveRecord::Base
belongs_to :project
belongs_to :user
has_one :project_as_authorized_user
end然后让has_one project_as_authorized_user关系将你的belongs_to authorized_project_user归零
发布于 2010-09-25 02:48:32
就我个人而言,我可能会考虑简化/分离关注点。下面是一个示例(注意:未测试):
class Project < ActiveRecord::Base
has_many :project_users
has_many :users, :through => :project_users
has_one :authoritative_user
end
class ProjectUser < ActiveRecord::Base
belongs_to :project
belongs_to :user
end
class AuthoritativeUser < ActiveRecord::Base
belongs_to :project
belongs_to :user
validates_uniqueness_of :user_id, :scope => :project_id
end实际上,我将ProjectUser模型的authoritative_user属性分解为它自己的属性。非常简单,干净,并不是很令人兴奋。
您可以在Project模型中构建一些方便的方法,如has_authoritative_user?和update_authoritative_user。
我相信你会得到一些更好的建议。
希望这能有所帮助!
https://stackoverflow.com/questions/3789364
复制相似问题