我的工作范围如下:
这是product.rb:
    has_one :current_price, -> {
    where('prices.id = (SELECT MAX(id) FROM prices p2 WHERE product_id = prices.product_id)') 
  }, class_name: 'Price'我正在尝试获取特定产品的当前价格,并且在不使用include()的情况下获取产品数据。
这是product_controller.rb:
  def current_price
    @product = Product.includes(:current_price).where("id = ?", params[:id])
    respond_to do |format|
      format.json { render :json => @product }
    end
  end例如,我得到了这个JSON:
{"id":10,"name":"Corneta Minipill","created_at":"2015-11-25T19:49:37.000-04:30","updated_at":"2015-11-25T19:49:37.000-04:30","published":null}我怀疑添加current_price结果的是同一个JSON,例如:
{"id":10,"name":"Corneta Minipill","created_at":"2015-11-25T19:49:37.000-04:30","updated_at":"2015-11-25T19:49:37.000-04:30","published":null,"current_price":"2000"}我以前使用过相同的includes(),它可以工作。
我已经尝试过用joins()和eager_load()代替joins()。
这是怎么回事?
发布于 2015-11-28 22:15:36
ActiveRecord::QueryMethods.includes只需要加载关联。
但是,它不会更改模型的序列化重新表示形式,因此关联的模型不会自动地包含在序列化结果中--您还必须对经过方法的to_json选项进行修改。
https://stackoverflow.com/questions/33976957
复制相似问题