【问题标题】:Rails table joinsRails 表连接
【发布时间】:2012-03-01 05:43:13
【问题描述】:

我正在尝试弄清楚如何在我的一个模型中进行表连接。

有积分、有问题、有用户。

point.rb

class Point < ActiveRecord::Base
    belongs_to :user
    belongs_to :question
end

question.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

在我的points/index视图中:

    <% @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,无法通过文档弄清楚如何做到这一点。

【问题讨论】:

    标签: ruby-on-rails join html-table arel


    【解决方案1】:

    如果您阅读了我之前的答案,请忽略它。我误读了你的问题。这应该可以。

    在你看来:

    <% user_points.questions.each do |question| %>
      ...Do whatever...
    <% end %>
    

    【讨论】:

      【解决方案2】:

      看看 Rails 指南,尤其是这两个:

      1. http://guides.rubyonrails.org/association_basics.html
      2. 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 %>
      

      【讨论】:

      • Simon - 现在解决这个问题...通过应该是 :through 在响应中(如果您可以编辑您的响应以使其他人受益,那就太好了),它有效! :) 我正在通过您提供的链接消化这一切是如何发生的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多