我正试图弄清楚如何在我的一个模型中进行表联接。
有要点、问题和用户。
点.rb
class Point < ActiveRecord::Base
belongs_to :user
belongs_to :question
end
问题.rb
class Question < ActiveRecord::Base
has_many :points
end
user.rb
class User < ActiveRecord::Base
在我的积分控制器中,我正在执行以下操作:
def index
@points = Point.all
@user_points = Point.where('user_id' => current_user)
end
在我的点/指数视图中:
<% @user_points.each do |user_point| %>
<tr>
<td><%= current_user.name %></td>
<td><%= user_point.question_id %></td>
<td><%= user_point.correct_answer %></td>
<td><%= user_point.user_answer %></td>
</tr>
<% end %>
我需要访问问题表中每个问题的名称(我的视图中有可用的问题id。我是rails的n00b,无法通过文档了解如何做到这一点。
如果你读了我以前的答案,忽略它。我误解了你的问题。这应该行得通。
在您看来:
<% user_points.questions.each do |question| %>
...Do whatever...
<% end %>
看看Rails指南,尤其是这两个:
- http://guides.rubyonrails.org/association_basics.html
- http://guides.rubyonrails.org/active_record_querying.html
我认为您应该能够在模型:中设置此项
class User < ActiveRecord::Base
has_many :points, :through => :questions
end
在控制器中说@user_points = current_user.points
在您的视图中。这应该已经适用于您当前的代码了!
<% @user_points.each do |user_point| %>
<td><%= user_point.question.name %></td>
<% end %>