变量作为rails

时间:2016-04-01 10:41:58

标签: ruby

我有两个型号(客户,产品)。它们与has_one关系相关联。目前我在做这个

@customer = Customer.first
@customer.product.name

此输出,产品的名称,这很好用。现在我想要这样的东西

product_type = "product"
@customer = Customer.first
@customer."#{product_type}".name

这应该像以前一样输出产品名称。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用类型,假设[:active, :sold, :not_active]是产品类型

class Customer < ActiveRecord::Base
   has_one :product
   [:active, :sold, :not_active].each do |type|
      define_method "#{type}" do
         product.where(type: type).first
      end
   end
end

现在@customer.active.name提供有效(类型)产品名称

@customer.sold.name提供已售出(类型)产品名称

@customer.not_active.name提供非活动(类型)产品名称

通过这种方式,您可以根据需要定义和调用所有其他类型