覆盖has_one的赋值方法

时间:2010-09-24 17:06:47

标签: ruby-on-rails ruby activerecord associations

我有一个反映另一个关联对象的has_one关联。我有Project,它有许多ProjectUsers,它们绑定了Projects和Users。其中一个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 =将更新项目用户以将权威设置为true,并使先前的权威用户将权威设置为false。我遇到的另一个问题是,第二次在项目上设置authoritative_user时,前一个ProjectUser上的project_id被设置为nil,因此它不再与Project的project_users相关联。

我不确定我是否只是完全错了,或者我错过了什么。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

就个人而言,我可能希望简化/分离问题。这是一个例子(注意:未经测试):

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

基本上,我将authoritative_user模型的ProjectUser属性划分为自己的属性。非常简单,干净而且不是很令人兴奋。

您可以在has_authoritative_user?模型中构建一些便捷方法,例如update_authoritative_userProject

我相信你会得到一些更好的建议。

希望这有帮助!