如何在rails中使用include条件获取值?

时间:2013-04-05 06:47:40

标签: ruby-on-rails ruby-on-rails-3

我的商店有has_many协会,并包含商品,以便收到属于该商店的商品

 format.json { render json: {:shop => @shops.as_json(:include => :items)}}

现在它提供了属于该商店的所有商品,但我想获得具有特定条件的商品,比如item_type =“accessories”。那怎么能这样呢?请帮帮我。

修改

我在How to get the value of include with conditions?

中提出了一个新问题

2 个答案:

答案 0 :(得分:1)

您应该使用ActiveRecord过滤数据,然后在过滤后的数据上调用as_json。

您可以执行以下操作:

@shops = Shop.includes(:items).where("items.itemp_type = ?", 'accesories')
format.json { render json: { :shop => @shops.as_json(:include => :items) } }

答案 1 :(得分:0)

您可以这样做的一种方法是使用要渲染的对象创建哈希,然后将其传递给render方法。像这样:

respond_to do |format|
  format.json  { render :json => {:shops => @shops, 
                                  :items => @items }}
end

如果模型没有通过活动记录关联,那可能是您的最佳解决方案。

如果存在关联,您可以传递:include argument to the render call,如下所示:

respond_to do |format|
  format.json  { render :json => @shops.to_json(:include => [:items])}
end

请注意,如果您采用这种方法,则不必在上面的部分中检索@items变量,Rails会自动从@shops变量加载它。