I have 2 models: AvailableDates --> belongs_to :spec and Spec --> has_many :available_dates Now I have a view where I want to show data from both Spec and AvailableDates whith the same friend_id attribute. I can do this with SQL, which works fine:
我有两个模型:有效日期——> belongs_to:spec和spec——> has_many:available_dates现在我有了一个视图,在这个视图中,我希望显示来自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'
The view will look like this, with data from both models:
视图是这样的,两个模型的数据如下:
<% @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 %>
However, this doesn't feel "rails like", so I want to do it this way, while keeping the code in the view unchanged:
然而,这并不像“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
Does anyone have a better solution? Thanks!
有人有更好的解决方案吗?谢谢!
Update: I now have this which works:
更新:我现在有了这个可以工作的:
@invitees = Friend.find(:all, :include => [:available_date, :spec], :conditions => ["specs.country = ?", "United Kingdom"])
But it only gives me data from Friend. How do I also get data from the associated available_date and spec?
但它只给我朋友的数据。如何从关联的available_date和spec中获取数据?
2 个解决方案
#1
5
You probably want to use the joins
or include
parameters to ActiveRecord's find
method. Take a look at the API documentation for find
and the Railscasts episode that explains the difference between the two.
您可能想要使用联结或包含ActiveRecord查找方法的参数。看看find和railscast的API文档,它们解释了两者之间的差异。
#2
0
After you have done the :include you can access the associated data like this:
完成:include后,您可以访问相关数据如下:
@invitees.each do |invite|
invite.available_date.city
invite.spec.first_name
end
#1
5
You probably want to use the joins
or include
parameters to ActiveRecord's find
method. Take a look at the API documentation for find
and the Railscasts episode that explains the difference between the two.
您可能想要使用联结或包含ActiveRecord查找方法的参数。看看find和railscast的API文档,它们解释了两者之间的差异。
#2
0
After you have done the :include you can access the associated data like this:
完成:include后,您可以访问相关数据如下:
@invitees.each do |invite|
invite.available_date.city
invite.spec.first_name
end