问题描述
所以我工作的地方有构成寻宝任务的项目。因此,当用户点击一个特定的狩猎,我想的show.html.erb文件显示狩猎,以及与狩猎相关的任务。这两种型号(Hunt.rb和Task.rb)与另一个has_and_belongs_to_many的关系。我控制器最初有这个code,但它表现的不是只与一个特定的狩猎相关的任务数据库中的每一项工作。
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
这里的show.html.erb:
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?
推荐答案
我建议你考虑从 has_and_belongs_to_many
切换到的has_many:通过=&GT; TBL
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.
我通常不指向API的时候人有问题,但在这种情况下实际上确实有很好的信息和示例。
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.
这篇关于有属于许多错误 - * _development.hunts_tasks'不存在:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!