Frage

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
War es hilfreich?

Lösung

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

Andere Tipps

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top