Reputation: 289
I have two methods in a class one tries to find a record in the database and returns it if it exists.The second one is executed only if the first doesn't find any result, and it creates a new record with the new
ActiveRecord method
i was suggested that I could replace both methods with only one ActiveRecord call but cant seem to find out how.
methods:
def find_cart_item
@cartitem = @cart.cart_items.find_by product_id: @product.id
end
def create_cart_item
@cartitem = @cart.cart_items.new(quantity: 0, price: @product.price, product: @product)
end
Any suggestions?
Upvotes: 0
Views: 685
Reputation: 6263
I think what you are looking for is
Cart.find_or_create_by(product_id: @product.id) do |c|
c.quantity = 0
c.price = @product.price
end
See the rails guides for a detailed explaination.
Note that quantity should probably default to zero (to make your code cleaner) and therefore be exclude, but I have included it incase you don't have a default.
Upvotes: 2
Reputation: 33542
You can use first_or_create!
or first_or_initialize
Cart.first_or_create!(product_id: @product.id) do |ct|
ct.quantity = 0
ct.price = @product.price
ct.product_id @product.id
end
or
@cart.cart_items.where(quantity: 0, price: @product.price, product_id: @product.id)
.first_or_create!
And also see this for 10 most magical Active Record
Queries.You would love it!
Upvotes: 1
Reputation: 29349
If you are using rails 4, you can do
@cart
.cart_items
.where(quantity: 0, price: @product.price, product_id: @product.id)
.first_or_initialize
you can also use find_or_create
if you want to create the object in the database
If you are using rails 3 or lower , you can do
@cart
.cart_items
.find_or_initialize_by_quantity_and_price_and_product_id(0, @product.price, @product.id)
you can also use find_or_create_by_quantity_and_price_and_product_id
if you want to create the object in the database
Upvotes: 3