2014-06-18 77 views
0

我有一個用戶模型,它通過UserRelationship連接表連接到另一個用戶模型。 UserRelationships具有必須設置的屬性(已批准/待定/已撤銷),但不會默認爲任何選項。有兩個協會反映這一點,旅行家和代表,所以我的模型是這樣的:<<如何加入具有集合屬性的模型

User.rb 
    has_many :traveler_relationships, :class_name => 'UserRelationship', :foreign_key => :delegate_id 
    has_many :travelers, :class_name => 'User', :through => :traveler_relationships 

    has_many :delegate_relationships, :class_name => 'UserRelationship', :foreign_key => :user_id 
    has_many :delegates, :class_name => 'User', :through => :delegate_relationships 

    has_many :buddy_relationships, class_name: 'UserRelationship', foreign_key: :user_id 
    has_many :buddies, class_name: 'User', through: :buddy_relationships, source: :delegate 


UserRelationship.rb 
    belongs_to :relationship_status 
    belongs_to :traveler, :class_name => 'User', :foreign_key => 'user_id' 
    belongs_to :delegate, :class_name => 'User' 

    PENDING = 1 
    CONFIRMED = 3 
    REVOKED = 5 

我試着寫了一些規範,其中一個用戶是另一併把它寫會的最簡單方法爲@user1.travelers << @user2,但是這會使UserRelationship.relationship_status不是null的數據庫約束失敗。

當我嘗試@user1.buddies.create(delegate: @user2, relationship_status: RelationshipStatus::CONFIRMED)時,它在delegate上沒有說UnknownAttributeError。我查看了this question並試用了它的解決方案,使用attr_acessible,但它並沒有改變UnknownAttributeError

創建具有屬性集的連接記錄的方式是什麼?

+0

用戶如何連接到他們的好友?我看到旅行者和代表,但在模型聲明中沒有提到夥伴。 – Sharagoz

+0

@Sharagoz抱歉,夥伴們是我忘記包括在這裏的代表的同義詞。看到我最新的編輯 – ABMagil

回答

0

我認爲UserRelationship有委託

class User < ActiveRecord::Base 
    has_many :traveler_relationships, :class_name => 'UserRelationship', :foreign_key => :user_id 
    has_many :delegate_relationships, :class_name => 'UserRelationship', :foreign_key => :delegate_id 

    has_many :travelers, :class_name => 'User', :through => :traveler_relationships 
    has_many :delegates, :class_name => 'User', :through => :delegate_relationships 
end 

class UserRelationship < ActiveRecord::Base 
    belongs_to :traveler, :class_name => 'User', :foreign_key => :user_id 
    belongs_to :delegate, :class_name => 'User', :foreign_key => :delegate_id 

    PENDING = 1 
    CONFIRMED = 3 
    REVOKED = 5 
end 

我不認爲你可以使用快捷@user1.delegates << @user2因爲你需要指定的關係狀態foreign_key delegate_id。嘗試:

@user1.traveler_relationships.create(delegate: @user2, relationship_status: RelationshipStatus::CONFIRMED) 

我在這裏排除了好友的同義詞。它現在很複雜。當這個工程,你可以看看添加同義詞。

0

當您嘗試從buddies(我假設這是您的連接模型關係)創建時,您處於正確的軌道上。問題是您的列名是relationship_status,並且您通過statuscreate。試試這個:

@user1.buddies.create(delegate: @user2, relationship_status: RelationshipStatus::CONFIRMED 
+0

這是一個很好的抓住,我也會解決它,但我仍然'UnknownAttributeError:未知屬性:委託' – ABMagil

相關問題