I have one model which has a foreign key :
class Hotel < ActiveRecord::Base
belongs_to :country
scope :country, lambda { |country_id|
开发者_Python百科self.scoped.where('country_id IN ( ? )', country_id) unless country_id.blank?
}
end
And in my controller, i do this :
def filter
@hotels = Hotel.scoped
@hotels = @hotels.country(params[:country_id]) unless params[:country_id].blank?
count = @hotels.count
render :json => ['hotels' => @hotels, 'count' => count ]
end
But my json answer has the value country_id but not my contry entity, how can I force that?
Thank you.
You are using "country" as if it were scope, calling it on all Hotels. This isn't correct. I assume you are trying to get all Hotels that belong to country_id. You can do that like this:
@country = Country.find(params[:country_id])
render :json => ['hotels' => @country.hotels, 'country' => @country]
Does that solve your problem? Your question is a little confusing.
I have my answer, I have to use in my controller the :include parameter :
render :json => ['hotels' => @hotels, 'count' => count ], :include=> [:country, :city]
This will add my city and country models to my json answer.
Thank for help !!
精彩评论