Question

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
Was it helpful?

Solution

 def line_total
   quantity * Product.find(product_id).current_price
 end

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top