2011-03-01 41 views
0

我一直在嘗試通過簡單地將我的兩個主要列(簡單地說是兩個主列)簡化我以前的帖子的背景(從大約6小時前:https://stackoverflow.com/questions/5150031/linking-three-models-through-two-join-models) (屬性和用戶)通過一個連接模型(actorships)鏈接,其中我有兩個ID(property_id和user_id)和一個字符串列(角色),我會爲其添加純文本。但是,我甚至不知道如何在視圖中爲這個簡單的模型創建一個simle;我讀過幾十個關於has_many的文章:通過和額外的領域,仍然沒有線索怎麼做...任何人都有一個簡單的答案來實現這個?看來,如果我是使用.NET,我會約2個星期前完成......使用連接模型(has_many到)和額外字段創建和更新兩個模型

回答

0
class User < ActiveRecord::Base 
    has_many :properties, :through => :actorships 
    has_many :actorships 
end 

class Property < ActiveRecord::Base 
    has_many :users, :through => :actorships 
    has_many :actorships 
end 

class Actorship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :property 
end 

user = User.last 
new_actorship = user.actorships.create(:property=>Property.last, :role => 'omg') 
# => Actorship associated to User and Property, with role 'omg' 

user.properties 
# => [Property.last] 
+0

我假設這是在控制器中。你如何動態獲得'omg'(即從視圖內的collection_select)? – macro 2011-03-01 16:34:32

+0

我有這些參數,但似乎無法訪問散列內的特定符號。我可以使用user_id的current_user.id,但我不知道該如何處理角色。這不起作用:new_actorship = @ property.actorships.create(:user_id => current_user.id,:role => params [:property] [:actorship_attributes] .role)(也不是params [:property] [:actorship_attributes] );它返回nul或類似'---:role \ n'或散列本身。 – macro 2011-03-01 18:30:42

+0

我不知道角色是什麼。它是一個字符串值嗎?它是否與另一個對象有關聯? – Winfield 2011-03-01 19:23:23