【问题标题】:Can I make this Rails 4 named scope nicer我可以让这个 Rails 4 命名范围更好吗
【发布时间】:2013-09-19 22:52:44
【问题描述】:

如果我没记错的话,我相信这被称为命名范围。无论如何,有没有人知道更好/更有效的编码方式..

这是来自 Rails 4 模型

 def line_total
   product = Product.find_by_id(self.product_id)
   line_total = self.quantity * product.current_price
   return line_total
 end

【问题讨论】:

标签: ruby-on-rails model ruby-on-rails-4 named-scope


【解决方案1】:
 def line_total
   quantity * Product.find(product_id).current_price
 end

【讨论】:

    【解决方案2】:

    这不适合作为范围。像您定义的方法最有意义。不过方法可以简化。

    模型是否定义了与Product 的关联?像has_one :product 这样的东西?如果是这样,该方法可能如下所示:

    class Rails4Model < ActiveRecord::Base
    
      has_one :product
    
      def line_total
        quantity * product.current_price
      end
    
    end
    

    【讨论】:

    • 而且,如果您要在许多“模型”上调用此方法,您需要确保这些获取使用includes(:product),否则,每次调用模型时都会执行查询.line_total.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2020-07-01
    • 2017-11-06
    相关资源
    最近更新 更多