【问题标题】:How to access first_name and last_name from belongs_to assocation rails如何从 belongs_to 关联导轨访问 first_name 和 last_name
【发布时间】:2015-08-15 15:43:18
【问题描述】:

我正在尝试通过引用不同表中的 user_id 列来访问用户的 first_name 和 last_name(关联表的两列),但我不知道如何操作。有什么建议吗?

这是我尝试引用它的视图

<% @allhours.each do |hour| %>
  <tr id="dashfield">
  <td><%= hour.user_id %></td>
  <td><%= hour.assignment %></td>
  <td><%= hour.hours %></td>
  <td><%= hour.supervisor %></td>
  <td><%= hour.date %></td>
  <td><%=form_for(:hour_log, method: :put) do |f|%>
  <%= f.hidden_field :status, :value => 'Confirmed' %>
  <%= f.submit 'Validate'%>
  <%end%></td>
  </tr>
  <% end %>

我想将“user_id”(一个数字)替换为 first_name 和 last_name。谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    你必须喜欢:

    <td><%= hour.user.first_name %></td>
    <td><%= hour.user.last_name %></td>
    

    在控制器内部执行以下操作以避免N + 1 查询问题:

    @allhours = AllHours.includes(:user)
    # change the code as per your need, but idea is to include the `user`
    # association in advance.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多