我已經建立了用戶和輪迴之間的多對多關聯。我正在試圖存儲誰是特定旋轉的創建者。Rails:在多對多的關聯中添加信息
類用戶
has_many :rotazations
has_many :rotas, :through => :rotazations
類羅塔島
has_many :rotazations
has_many :users, :through => :rotazations, :order => 'name ASC'
類Rotazation
belongs_to :user
belongs_to :rota
before_create do |rotazation|
rotazation.creator_id = rotazation.user_id
end
當輪狀病毒被創建,我已經成功地在rotazation表中設置了creator_id以具有創建rota的用戶的id。我的問題是,我該如何訪問:
rota.creator
我嘗試
我試圖添加以下內容:
羅塔類
用戶分類
has_many :created_rotas, :class_name=> "Rota", :through => :rotazations, :foreign_key => "creator_id"
但是,這並不奏效。任何想法如何實現rota.creator工作?謝謝!
非常好的一點。所以它是用戶和Rota之間的多對一關係。我通常使用:user.rotas創建輪迴。創建 我想知道,我可以在創建rota時自動將創建者字段指向創建它的用戶來實現回調嗎? – Karan 2012-07-29 13:25:28
由於has_many通過關聯,你可以執行'user.rotas.create',否則你必須以用戶身份執行並且不能直接連接rota。我認爲你最好的選擇是在你的表格中加入一個hidden_field。我假設你有一個current_user助手,所以你可以包含'<%f.hidden_field:creator,:value => current_user.id%>'。每創建一個新的rota,'creator'都會存儲當前用戶的id。 – gabrielhilal 2012-07-29 13:35:28