所以我正在开展一个项目,其中有一些任务可以组成一个寻宝者。因此,当用户点击特定的搜索时,我希望show.html.erb文件显示搜索以及与该搜索相关的任务。两个模型(Hunt.rb和Task.rb)彼此之间具有“has_and_belongs_to_many”关系。我的控制器最初有这个代码,但它显示了数据库中的每个任务,而不仅仅是与特定搜索相关的任务。
def show
@hunt = Hunt.find(params[:id])
@title = @hunt.name
@tasks = Task.paginate(:page => params[:page])
end
所以我试过了。
def show
@hunt = Hunt.find(params[:id])
@title = @hunt.name
@tasks = @hunt.tasks.paginate(:page => params[:page])
end
然后它抛出了这个错误:
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
这是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>
任何想法我搞砸了什么?
答案 0 :(得分:2)
我建议您考虑从has_and_belongs_to_many
切换到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
从长远来看,您会发现它更灵活,更易于使用,因此这是一个更好的起点。
当人们有问题时,我通常不会指向api,但在这种情况下,the api确实有很好的信息和示例。