开发者

Show foreign key values with a json answer

开发者 https://www.devze.com 2023-04-12 00:40 出处:网络
I have one model which has a foreign key : class Hotel < ActiveRecord::Base belongs_to :country scope :country, lambda { |country_id|

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 !!

0

精彩评论

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