Model Methods


Premium Content - Free Preview

As with ordinary ruby classes, you can add methods to your product class. Before we do that, let's add a way to track how many items of each product are left in our inventory. Do that below and in your app.

Instance Method

Once you've added a quantity column, you can set the quantity of your products. Next, let's create a method purchase for purchasing a specific item.

class Product < ActiveRecord::Base
  #...

  def purchase
  end

end

Now we want to fill in the above purchase method so it decreases quantity by one.

We could use the standard update_attributes method:

 update_attributes(quantity: quantity - 1)

Rails also provides a useful method decrement to make this more concise:

  def purchase
    decrement(:quantity)
  end

Trying it out
Now that you have a purchase method, start your console and set the quantity of some products. For example:

 prod = Product.first # this returns the first product
 prod.quantity = 3
 prod.save

Now, try out the purchase method:

prod.purchase

output:

(0.3ms)  begin transaction
  SQL (0.5ms)  UPDATE "products" SET "quantity" = ?, "updated_at" = ? WHERE "products"."id" = ?  [["quantity", 2]....
   (2.1ms)  commit transaction
 => true 

Now prod's quantity is only 2, which you see by entering prod.quantity.

You can purchase it a few more times, and it will go down to 0:

prod.purchase
prod.purchase

What happens if you purchase it again?

prod.purchase
prod.quantity
=> -1

Oops. We don't want to allow a negative quantity. Let's adjust the purchase method to prevent that:

def purchase
    if quantity > 0            # line 2
        decrement(:quantity)   # line 3
        return true
    end
end

Now if you reload your console, you'll find that the quantity doesn't change when you try purchasing a product that's already at 0.

:symbols and variables

Question: In the purchase method above, we referred to quantity on its own in line 2, but we used the symbol :quantity in line 3. What's going on? And how could we refer to quantity if no variable like that had been set earlier in the code?

Answer: Rails automatically provides methods to get and set the columns of a model. So if you have a column in your model, you can use methods to get and set its values.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]