문제

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
도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top