Domanda

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
È stato utile?

Soluzione

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

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top