ana
ana

Reputation: 485

Ruby on Rails model relations, product with options

I have a model Product that can either have just a price, or a price that is connected to a length. I struggling with how to solve this. Which relation should the Product, price and length have? The result I want is that you when you´re looking at a product that has different lengths, you should be able to choose a length from a drop-down list and get the price updated. Been really stuck at this and appreciate all help!

Upvotes: 0

Views: 87

Answers (2)

abo-elleef
abo-elleef

Reputation: 2198

html

<ul>
  <% @products.each do |product| %>
    <li>
      <%= link to product.name, add_price_of_product_path(product),remote: true %></li>
<% end %>
</ul>

routes

resources :products do 
    member do
        get :add_price_of
    end
end

product controller

def add_price_of 
    #your code to add the price of the chosen product to the total price   
end

add add_price_of.js.erb file in the views/products directory and put java scripy code to update the price in the html dom

it would be nice if you notify the users that the price has been add

Upvotes: 0

Matthias
Matthias

Reputation: 4375

You could create a 1:n or a n:m association between the products and prices.

product for example has a name and color. prices for example has an amount.

@product = Product.first
if @product.prices.count > 1
   # render your dropdown field which contains a list of all @product.prices amounts.
else
  # render @product.prices.first amount
end

The rendering and updating in the view could be done through ajax, like @leef already said in his comment.

Upvotes: 1

Related Questions