coletrain
coletrain

Reputation: 2849

undefined method 'model_name' for class_name?

I am trying to grab a user job notes but am not sure what I am doing wrong. At first I was able to get the job and note working properly when I nested just the two but when I wanted to get the user job notes then my code broke.

notes.controller new

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

In rails console if I were to type the following code it works fine.

User.last.jobs

If I were to try to code below it does not

User.last.jobs.notes

then I get the error

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

How can I properly grab the user_id when creating a note for a job? right now it grabs the job id for the note but does not grab the user id. I would like to be able to find notes from a job and user. Any ideas what I am doing wrong and how I can fix this?

Upvotes: 0

Views: 397

Answers (3)

fagiani
fagiani

Reputation: 2341

As you are using has_many :through, you should just use:

User.last.notes

This will get the last user's notes through jobs

Upvotes: 1

ernd enson
ernd enson

Reputation: 1764

The basic fault is that you are asking through 2 has_many relations. This is not possible. You could do something like:

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

Upvotes: 1

ply
ply

Reputation: 1141

your notes model looks like it has a typo, should be

has_many :jobs

instead of

has_jobs

Upvotes: 0

Related Questions