0

I have two models(Customer, Product). They are associated with has_one relation. Currently I am doing this

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

This output, the name of the product and this works just fine. Now I want something like this

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

This should output product name like before. How can I achieve this?

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145

1 Answers1

0

You can try with types assuming [:active, :sold, :not_active] are the types of products

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

Now @customer.active.name give the active(type) product name

or @customer.sold.name give the sold(type) product name

or @customer.not_active.namegive the not active(type) product name

in this way you can define and call for all the other types as you need

Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74