0

私は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

ProjectDate に関連付けられたすべてのイベントも取得しているときに、イベントに関連付けられたユーザー属性を取得するためにインクルードを使用する方法 (またはインクルードを使用できるかどうか) を考えています。

user.firstname をプルできるようにしたい (以下のコードを参照)

これは、関連するイベントを含む ProjectDats の配列をフェッチする方法です。

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

私は本当に立ち往生しています。

ビューコードは次のとおりです。

    <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 %> 
4

1 に答える 1

1

このように include 引数をネストできます。

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

これevents: :userにより、イベントとそのユーザーの両方が熱心に読み込まれます。

于 2014-11-13T14:59:38.373 に答える