LearningRoR
LearningRoR

Reputation: 27232

How to show select menu for two models?

I'm using Simple Form and don't how you would show the values of 2 associations.

A Price can belong to a service or product but not both at the same time.

Price
 # service_id, product_id
 belongs_to :services # service.name
 belongs_to :products # product.name
end

Instead having my simple form look like this:

<%= f.association :product, :input_html => { :class => "span5 } %>
<%= f.association :service, :input_html => { :class => "span5 } %>

I want to turn it into one field instead.

What is the way with simple_form_for?

What about with a regular form_for?

Upvotes: 0

Views: 81

Answers (1)

Salil
Salil

Reputation: 9722

I think better way to do is to use polymorphic association.

class Price
    belongs_to :pricable, polymorphic: true
end

class Product
    has_one :price, as: :priceable
end

class Service
    has_one :price, as: :priceable
end

Then, in your form, you can use:

<%= form_for [@priceable, Price.new]

where @priceable is a product or a service.

Upvotes: 1

Related Questions