2010-09-24 34 views
0

我有一個has_one關聯,它反映了另一個關聯的對象。我有Project,它有很多ProjectUser,它們將項目和用戶聯繫在一起。其中一個ProjectUser是權威的。問題是has_one和has_many在project_users上使用相同的外鍵。這是模型的基本思想。覆蓋has_one的分配方法

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被設置爲零,因此它不再通過項目的project_users關聯。

我不確定我是否完全錯了,或者我只是錯過了一些東西。

回答

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

就我個人而言,我可能會考慮簡化/分離問題。下面是一個例子(注:未經測試):

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

我相信你會得到一些更好的建議。

希望這會有所幫助!

+0

我喜歡這個解決方案,如果authoritative_user沒得是可變的。如果ProjectUser上沒有其他列描述項目<=>用戶關係,我甚至可以看到工作,因此只有AuthoritativeUser上的用戶可以更改以反映誰是權威用戶,但不幸的是,有那些額外的數據。我可能會將所有額外的元數據抽象爲單獨的模型,並將其與ProjectUser/AuthoritativeUser關聯起來。我可能會說,因爲實際情況會需要2年的代碼進行大規模的可怕重構。 – lambdabutz 2010-09-24 20:30:09

+0

除非我失去了一些東西,authoritative_user肯定會改變(但是,只能有一個)。另外,沒有理由爲什麼'ProjectUser'模型不能有額外的屬性。畢竟,這就是爲什麼'has_many:through'關係存在的原因。 – Brian 2010-09-24 20:52:37