开发者

Get distinct values of an has_many field

I have a model :

class Hotel < ActiveRecord::Base
   has_many :hotel_comments
end

In my controller开发者_如何学Python, i get some hotels:

@hotels = Hotel.all

How can I get all comments for my hotel dictionary?

Thank you!


Guessing what you mean by "dictionary":

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

If you just want all comments in a array:

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


Without seeing more of your model, I am also guessing a bit here too, but how about:

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

Or, if HotelComments is large, something like:

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

... would gather up the comments with one pass through HotelComments

You may find (much) better thoughts here: http://guides.rubyonrails.org/active_record_querying.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜