2

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. Both models (Hunt.rb and Task.rb) have "has_and_belongs_to_many" relationships with one another. My controller originally had this code, but it showed every task in the database, instead of just the tasks associated with a particular hunt.

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

So I tried this.

  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:

    ActiveRecord::StatementInvalid in Hunts#show
    Showing /****/views/hunts/show.html.erb where line #10 raised:
    Mysql2::Error: Table '***_development.hunts_tasks' doesn't exist: SELECT  `tasks`.* FROM `tasks` INNER JOIN `hunts_tasks` ON `tasks`.`id` = `hunts_tasks`.`task_id` WHERE `hunts_tasks`.`hunt_id` = 100 LIMIT 30 OFFSET 0

Here's the show.html.erb:

    <h1>Show Hunt</h1>

    <table>
      <tr>
        <td class="main">
          <h1>
            <%= @hunt.name %>
          </h1>
            <ul>        
              <% @tasks.each do |task| %>
                 <%= render task  %>
              <% end %>
            </ul>
        </td>
      </tr>
    </table>

Any ideas what I'm messing up?

tereško
  • 58,060
  • 25
  • 98
  • 150
Ben Downey
  • 2,575
  • 4
  • 37
  • 57
  • 2
    Have you created the `hunts_tasks` join table. – Frederick Cheung Mar 31 '12 at 16:39
  • 1
    Did you create the `hunts_tasks` table? I believe `has_and_belongs_to_many` requires you to still create a table to represent the relationship. In this case it's just a simple table with `hunt_id` and `task_id`. See the [documentation](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many) – Jeff Smith Mar 31 '12 at 16:44

1 Answers1

2

I suggest you consider switching from has_and_belongs_to_many to has_many :through => tbl

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

class HuntTask < ActiveRecord::Base

  belongs_to :hunt
  belongs_to :task

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

You'll find it more flexible and easier to use in the long term so it's a better place to start.

I don't normally point to api's when folks have questions but in this case the api does actually have good info and examples.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497