如何获得包含条件的值? [英] How to get the value of include with conditions?
问题描述
我有三个表,分别是 shop、item 和 item_type
I have three table say shop, item and item_type
商店包含商店名称,item 包含每个商店的商品,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.
现在我要渲染
format.json { render json: {:shop => @shops.as_json(:include => :items)}}
但根据条件,说出 item_type_id='1' 和 item_type_status='available' 状态的项目
but based on the condition, say items with the item_type_id='1' and status of the item_type_status='available'
推荐答案
试试这个:
@shops = Shop.includes(:items).where("items.itemp_type = ?", 'accesories')
format.json { render json: { :shop => @shops.as_json(:include => :items) } }
已
您可以执行此操作的一种方法是使用您要渲染的对象创建一个散列,然后将其传递给渲染方法.像这样:
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.
如果关联确实存在,您可以将 :include 参数传递给渲染调用,如下所示:
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
请注意,如果您采用这种方法,则不必在上一节中检索 @items 变量,Rails 会自动从 @shops 变量中加载它.
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.
这篇关于如何获得包含条件的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!