简体   繁体   English

在轨道4中使用包含和深层嵌套

[英]Using includes with deep nesting in rails 4

I have 3 Models. 我有3个模型。

  ProjectDate (available dates for a project) which 
  has_many Events

  Events (the appointments on any given ProjectDate)
  belongs_to ProjectDate
  belongs_to User

  User (the person who created the Event)
  has_many Events

I am wondering how I can use includes (or if I can use includes) to fetch the User attributes associated with an Event when I'm also fetching all the Events associated with a ProjectDate. 我想知道当我也要获取与ProjectDate相关的所有事件时,如何使用包含(或是否可以使用包含)来获取与事件相关的用户属性。

I want to be able to pull the user.firstname (see view code below) 我希望能够拉出user.firstname(请参见下面的查看代码)

This is how I fetch an array of ProjectDats with their associated Events: 这就是我如何获取带有相关事件的ProjectDat数组:

     @projectschedule  = ProjectDate.where(project_id: params[:p]).includes(:events).order(the_date: :asc)

I am really stuck. 我真的被困住了。

Here is the view code: 这是视图代码:

    <table width="100%;" class="">
      <tr>
        <td >
          <%=p.the_date.strftime("%A")%><br>
            <%=p.the_date.strftime("%b. %d ")%>
          </td>
          <td class="dateinfo"><%   p.events.users.each do |e| %>
             <ul >
               <li ><%= e.starts_on.strftime("%l:%m %P ") %><%= e.user.firstname %><%= e.description %><button >O</button><button >O</button></li>
            </ul><% end %> 
           </td>
         </tr>
       </table>
 <% end %> 

You can nest include arguments like this. 您可以嵌套包含这样的参数。

@projectschedule  = ProjectDate.where(project_id: params[:p]).includes(events: :user).order(the_date: :asc)

Note events: :user , which will make sure both events and it's user are eager loaded. 注意events: :user ,这将确保两个事件及其用户都已被加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM