问题
I have three table say shop, item and item_type
the shop contains names of shops and item contains items of each shop and item_type contains different types of that items along with the status such as available or not available.
Now i want to render
format.json { render json: {:shop => @shops.as_json(:include => :items)}}
but based on the condition, say items with the item_type_id='1' and status of the item_type_status='available'
回答1:
Try this:
@shops = Shop.includes(:items).where("items.itemp_type = ?", 'accesories')
format.json { render json: { :shop => @shops.as_json(:include => :items) } }
Edited:
One way you could do this is to create a hash with the objects you want to render, and then pass that to the render method. Like so:
respond_to do |format|
format.json { render :json => {:shops => @shops,
:items => @items }}
end
If the models aren't associated through active record, that's probably your best solution.
If an association does exist, you can pass an :include argument to the render call, like so:
respond_to do |format|
format.json { render :json => @shops.to_json(:include => [:items])}
end
Note that you wouldn't have to retrieve the @items variable in the section above if you take this approach, Rails will automatically load it from the @shops variable.
回答2:
You can pass method or methods to to_json or as_json methods and include needed records. Example from Rails api:
user.as_json(:methods => :permalink)
# => {"id": 1, "name": "Konata Izumi", "age": 16,
"created_at": "2006/08/01", "awesome": true,
"permalink": "1-konata-izumi"}
来源:https://stackoverflow.com/questions/15829497/how-to-get-the-value-of-include-with-conditions