ruby-on-railsassociations

Rails belongs_to includes select query - ActiveModel::MissingAttributeError


I have two tables:

class Order < ActiveRecord::Base
   has_many :order_lines
end
class OrderLine < ActiveRecord::Base
   belongs_to :order
end

I have a workflow in the code that generates below query:

OrderLine.includes(:order).select(:id).first

However, the above query results in ActiveModel::MissingAttributeError: missing attribute: order_id. I don't understand why am i getting this error. And how to fix it?

Thanks in Advance


Solution

  • That's because of this;

    class ActiveRecord::Associations::Preloader::Association::LoaderRecords
      ...
    
      def owner_key_name
        reflection.join_foreign_key
      end
    end
    

    which extracts the foreign key of the table that's in the includes call. As ActiveRecord needs to know how to join which tables and load which records, then order_lines.order_id becomes a mandatory column in your select clause.

    To fix it, just add the order_id column to your select;

    OrderLine.includes(:order).select(:id, :order_id).first