Question

Was following the Depot application from Agile Web Development with Rails. There was a method I got confused. I thought I understood it until I tried it in irb. So here's the method:

  def add_product(product_id)
    current_item = line_items.find_by_product_id(product_id)
    if current_item
      current_item.quantity += 1
    else
      current_item = line_items.build(product_id: product_id)
    end

    current_item
  end

From what I understood, It's just a method that will first find a record in LineItems with a product ID of an give input (let's say it's 10). Then it will store it in current_item variable. The condition says 'If the product id was found, add 1 to quantity else create a new instance of that record with the product id equals to 10'

Here's the snapshot of my rails console

enter image description here

As you can see, product id of 10 in LineItem is not found. But on my condition, it goes against everything that I believe until now. Could someone shed a light on this?

Was it helpful?

Solution

Looks like line is an empty collection (ActiveRecord::Relation to be exact) and so it's something in Ruby and not nil. That's why it's returning true when you're calling if line and executing puts 'I'm true and happy'.The reason it's an ActiveRecord::Relation is because you're using the where query.

In the Depot application they're making the query by calling line_items.find_by_product_id(product_id) which is different. It finds the first record matching the condition.

Check out the Rails guides here for more info - http://guides.rubyonrails.org/active_record_querying.html (section 15)

PS Looks like that type of query is deprecated in Rails 4 so not sure what version of Agile Web Development with Rails you're looking at.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top