Reputation: 34
I am getting undefined method error in my rails console if I try to get something from model SubQuantity
I have a model called Subquantity
, right now in my model I have
SubQuantity.rb
belongs_to :product
belongs_to :cart
end
and I have an integer defined in SubQuantity
model called sub_quantity
. In my code I am trying to do something like this
subq = SubQuantity.where(product_id:@product.id, cart_id:current_user.cart.id)
in return I am getting this,
[#<SubQuantity:0x007fbbdc046d08
id: 4,
sub_quantity: 1,
product_id: 4,
cart_id: 6,
created_at: Sun, 22 May 2016 11:03:55 UTC +00:00,
updated_at: Sun, 22 May 2016 11:03:55 UTC +00:00>]
and whenever I try to do something like this,
subq.sub_quantity
I am getting this error,
NoMethodError: undefined method sub_quantity for
#<SubQuantity::ActiveRecord_Relation:0x007fbbdc04d838>
.
This is not only with sub_quantity, I am getting exact errors for every thing in subq even with subq.id.
What is wrong here ?
Upvotes: 0
Views: 1099
Reputation: 577
Whenever you use where
method, it returns an array even if the result is one object. To fix your problem you must call .first
, to extract the first result from the array (in this case is the only one). Example:
subq = SubQuantity.where(product_id: @product.id, cart_id: current_user.cart.id)
subq.first.sub_quantity
Another way, without first
would be to use find_by
. It works just like where
method but returns exactly one result, the first one it can find.
subq = SubQuantity.find_by(product_id: @product.id, cart_id: current_user.cart.id)
subq.sub_quantity
Upvotes: 1