2012-06-24 19 views
0

我想抓住一個用戶的工作筆記,但不知道我做錯了什麼。起初,我能夠得到這份工作,並注意到當我嵌套兩者時正常工作,但是當我想要獲取用戶作業筆記時,我的代碼被破壞了。未定義的方法'model_name'for class_name?

notes.controller新

def new 
    @note = @user_note.notes.new 
end 

private 

def user_note 
    @user = current_user 
    @job = @user.job.find(params[:job_id]) 
end 

user.rb

has_many :jobs 
has_many :notes, through: :jobs 

job.rb

belongs_to :user 
belongs_to :note 

notes.rb

has_many :jobs 
has_many :users, through: :jobs 

在軌控制檯如果我鍵入下面的代碼,它工作正常。

User.last.jobs 

如果我嘗試下面的代碼它不

User.last.jobs.notes 

然後我得到的錯誤

undefined method `notes' for #<Job:0x007fe37dc77190> 

如何爲創建記事時,我適當地搶USER_ID工作?現在它抓取註釋的作業ID,但不抓取用戶ID。我希望能夠找到工作和用戶的筆記。任何想法我做錯了,我該如何解決這個問題?

回答

1

基本的故障原因是,你問過2個的has_many關係。這不可能。你可以這樣做:當你正在使用has_many :through

user = User.last 
user.jobs # returns all the user's jobs 
user.notes # returns all the user's notes 
user.jobs.each_with_object({}) {|job, hash| hash[:job.id] = job.note_ids]} 
    # returns a hash with user's job_id as keys and an array of related note_ids as value 
0

筆記模型看起來有一個錯字,應該是

has_many :jobs 

,而不是

has_jobs 
1

,你應該只使用:

User.last.notes

這將通過工作得到最後一個用戶的筆記