Alejandro Araujo
Alejandro Araujo

Reputation: 149

Simple includes() is not working

I have the following scope:

This is product.rb:

    has_one :current_price, -> {
    where('prices.id = (SELECT MAX(id) FROM prices p2 WHERE product_id = prices.product_id)') 
  }, class_name: 'Price'

I'm trying to get the current price of a specific product and I'm getting the product data without the include().

This is 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

For example, Im getting this 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}

Im specting the same JSON adding current_price result, for example:

{"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"}

I used the same includes() before and it works.

I already tried replacing includes() with joins() and eager_load().

What is happening?

Upvotes: 0

Views: 70

Answers (1)

lorefnon
lorefnon

Reputation: 13095

ActiveRecord::QueryMethods.includes only eager loads the associations.

It does not however change the serialized respresentation of the models, so the associated models will not be auto-magically included in the serialized result - you will have to pass the includes option to the to_json method as well.

Upvotes: 3

Related Questions