获取has_many字段的不同值

时间:2011-10-07 15:53:19

标签: ruby ruby-on-rails-3

我有一个模特:

class Hotel < ActiveRecord::Base
   has_many :hotel_comments
end

在我的控制器中,我找到了一些酒店:

@hotels = Hotel.all

如何获取酒店词典的所有评论?

谢谢!

2 个答案:

答案 0 :(得分:1)

猜猜你的意思是“字典”:

Hash[Hotel.includes(:hotel_comments).map { |h| [h, h.hotel_comments] }]

如果您只想要数组中的所有注释:

Hotel.includes(:hotel_comments).map(&:hotel_comments).flatten(1)

答案 1 :(得分:0)

如果没有看到更多的模型,我也会在这里猜测一下,但是如何:

@biglist=new(array)
@hotels.for_each do |h|
    sub_list=HotelComments.find_by_hotel_id(h.id)
    @big_list.push(sub_list)
end

或者,如果酒店评论规模很大,可以这样:

@biglist=new(array)
ids=new(array)
@hotels.for_each do |h|
    ids.push(h.id)
end
@big_list=HotelComments.find_by_hotel_id(ids)

...将通过HotelComments

收集评论

您可以在这里找到(更多)更好的想法:http://guides.rubyonrails.org/active_record_querying.html