2014-12-23 130 views
0

我正在構建一個Project應用程序,我需要自動生成1個參與者創建項目記錄。在創建父記錄後自動創建關聯記錄

My model 

class Project < ActiveRecord::Base 
has_many :participants, dependent: :destroy, inverse_of: :project 

after_create :build_a_role 

private 
    def build_a_role 
    self.participant.create!(user_id: current_user.id, level: 1, participant_cat: @role.id, added_by: current_user.id) 
    end 

end 

當我嘗試這個,我得到這個錯誤:

undefined method `participant' for #<Project:0x007fb402707250> 

回答

1

你在你的代碼中的錯字。

以下:

self.participant.create 

應該是:

self.participants.create 

由於模型has_many :participants,不has_one :participant

我也看到你在你的模型中使用current_user@role。如果你期待他們被控制器轉發他們,那麼這不會發生。該幫助器和變量在模型中將不可訪問,並且即使在修復了上述錯字之後,也會使您的方法崩潰。

如果您的項目以某種方式存儲用戶和角色,我建議您從self對象中創建參與者。

+0

啊,謝謝。我的項目確實將current_user存儲爲user_id ...來訪問它們,我會寫self.participants.create!(user_id::user_id級別:1,participant_cat :: role,added_by :: user_id)? – NothingToSeeHere

+1

'self.participants.create!(user_id:self.user_id,level:1,participant_cat:self.role,added_by:self.user_id)' 將我的回覆標記爲一個,如果它回答您的問題。 – Humza