Has and Belongs to Many error - *_development.hunt

2020-03-07 05:03发布

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?

1条回答
Root(大扎)
2楼-- · 2020-03-07 05:28

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.

查看更多
登录 后发表回答