Ben Downey
Ben Downey

Reputation: 2665

NameError in Controller due to wrong syntax in join table

So I'm working on a project where there are tasks that make up a scavenger hunt. So when a user clicks on a particular hunt, I'd like the show.html.erb file to show the hunt as well as the tasks associated with that hunt. I've got the hunt and tasks models connected through HuntTask.rb. I created the HuntTask model based off a suggestion here: Has and Belongs to Many error - *_development.hunts_tasks' doesn't exist:, but I'm still having trouble getting the hunt controller to make sense.

  def show
    @hunt = Hunt.find(params[:id])
    @title = @hunt.name    
    @tasks = @hunt.tasks.paginate(:page => params[:page]) 
  end

But then it throws up this error:

    NameError in HuntsController#show
    uninitialized constant Hunt::Hunttask

Here's what my models looks like:

class Hunt < ActiveRecord::Base
  has_many :hunttasks
  has_many :tasks, :through => :hunttasks
end

class Task < ActiveRecord::Base
  has_many :hunttasks
  has_many :hunts, :through => :hunttasks
end

class HuntTask < ActiveRecord::Base

  belongs_to :hunt, :class_name => "Hunt"
  belongs_to :task, :class_name => "Task"

I'm pretty sure that the name error is telling me that Rails can't find a table called hunt," which makes sense because the correct table is "hunts." But I'm hesitant to change the third line of my show method,

@tasks = @hunt.tasks.paginate(:page => params[:page]) 

because I want to specify that the @tasks method should pull all the tasks associated with this particular hunt being shown, not with all hunts. I suppose I just don't understand the syntax I'm using in @tasks.

When I do add the s to (@tasks = @hunts.tasks.paginate(:page => params[:page]) ), I get a NilClass error.

NoMethodError in HuntsController#show
undefined method `tasks' for nil:NilClass

But I don't think tasks is supposed to be a method. Or is it?

Any advice on what I should be doing?

Upvotes: 0

Views: 183

Answers (1)

ecoologic
ecoologic

Reputation: 10420

I think this should be:

class Hunt < ActiveRecord::Base
  has_many :hunt_tasks
  has_many :tasks, :through => :hunt_tasks
end

class Task < ActiveRecord::Base
  has_many :hunt_tasks
  has_many :hunts, :through => :hunt_tasks
end

class HuntTask < ActiveRecord::Base  
  belongs_to :hunt # the id for the association is in this table
  belongs_to :task
end

when you're doing something like belongs_to :hunt, :class_name => "Hunt" which seems pretty straight forward and you didn't need to do elsewhere, you should ask yourself why.

Upvotes: 1

Related Questions