代码之家  ›  专栏  ›  技术社区  ›  John

在一个视图中显示来自两个模型的数据

  •  3
  • John  · 技术社区  · 15 年前

    我有两个型号:AvailableDates-->属于:spec和spec-->有许多:可用的日期 现在我有了一个视图,我想在其中显示来自spec和availabledates的数据,这些数据具有相同的friend_id属性。我可以用SQL来实现这一点,它工作得很好:

    @invitees = AvailableDate.find_by_sql "SELECT d.friend_id, s.first_name, s.last_name, s.gender, s.birthdate, s.occupation, s.country, s.city FROM available_dates d, specs s WHERE d.friend_id = s.friend_id AND d.city = 'London'
    

    视图将如下所示,其中包含来自两个模型的数据:

        <% @invitees.each do |invitee| %>
          <tr>
            <td><%=h invitee.first_name %></td>
            <td><%=h invitee.last_name %></td>
            <td><%=h invitee.gender %></td>
            <td><%=h invitee.birthdate %></td>
          </tr>
        <% end %>
    

    但是,这感觉不像是“Rails”,所以我想这样做,同时保持视图中的代码不变:

    @invitees = AvailableDate.find(:all, :conditions => ["country = ? and city = ? and start_date <= ? and end_date >= ?", country, city, date, date])
    
        # Retrieve spec data for every matching invitee
        @invitees.each do |invitee|
          @spec = Spec.find(:first, :conditions => ["friend_id = ?", invitee.friend_id])
        end  
    

    有人有更好的解决方案吗?谢谢!

    更新:我现在有了这个,它可以工作:

    @invitees = Friend.find(:all, :include => [:available_date, :spec], :conditions => ["specs.country = ?", "United Kingdom"])
    

    但它只给我朋友的数据。如何从相关的可用日期和规格中获取数据?

    2 回复  |  直到 15 年前
        1
  •  5
  •   Jimmy Nitzan Tomer    15 年前
        2
  •  0
  •   DanneManne    15 年前

    @invitees.each do |invite|
      invite.available_date.city
      invite.spec.first_name
    end