-1

I believe this is called a named scope, if I am not mistaken. At any rate, does anyone know of a better / more efficient way of coding this..

This is from a Rails 4 Model

 def line_total
   product = Product.find_by_id(self.product_id)
   line_total = self.quantity * product.current_price
   return line_total
 end
Marcelo De Polli
  • 28,123
  • 4
  • 37
  • 47
Jakcst
  • 605
  • 3
  • 8
  • 16
  • What kind of answer are you wishing for? One reading I can recommend is: http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html – vee Sep 19 '13 at 22:57
  • This isn't a scope, it's just a method. And "more efficient"? You're multiplying two numbers together. Efficiency doesn't enter into it. – user229044 Sep 19 '13 at 23:01

2 Answers2

1

This isn't appropriate as a scope. A method like you have defined makes the most sense. The method could be simplified though.

Does the model have an association defined to Product? Something like has_one :product? If so, the method could look like this:

class Rails4Model < ActiveRecord::Base

  has_one :product

  def line_total
    quantity * product.current_price
  end

end
osahyoun
  • 5,173
  • 2
  • 17
  • 15
Ross Allen
  • 43,772
  • 14
  • 97
  • 95
  • And, if you are going to call this method on many "Models", you would want to make sure that those fetches use `includes(:product)`, otherwise, a query will be executed every time you call model.line_total. – steakchaser Sep 19 '13 at 23:02
1
 def line_total
   quantity * Product.find(product_id).current_price
 end
Ayman
  • 306
  • 2
  • 4