Has and Belongs to Many error - *_development.hunts_tasks' doesn't exist:

扶醉桌前 提交于 2019-11-30 19:35:47

问题


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:


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.



来源:https://stackoverflow.com/questions/9957719/has-and-belongs-to-many-error-development-hunts-tasks-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!