开发者

Rails way to set up relationship for this model

Being new at Ruby and Rails, I wasn't sure how to explain this in my title so i will do it here. My goal is to create many Products and with those have only one overall Location per submit.

I have a Product MVC and a quick ugly sketch of the form would be something like this:

Overall Location

form_for @product

<p>
<%= f.label :location %>:<br>
<%= f.text_field :location %>
</p>

Product one

<p>
<%= f.label :name %>:<br>
<%= f.text_field :name %>
<%= f.label :price %>:<br>
<%= f.text_field :price %>
</p>

Product Two (same)

<p>
<%= f.la开发者_如何学编程bel :name %>:<br>
<%= f.text_field :name %>
<%= f.label :price %>:<br>
<%= f.text_field :price %>
</p>

Product Three(same)

<p>
<%= f.label :name %>:<br>
<%= f.text_field :name %>
<%= f.label :price %>:<br>
<%= f.text_field :price %>
</p>

<%= f.submit %> 
<% end %>

How would you set it up so this relationship could take place so when a user creates 3 products on a form, he has only one location for all 3 of them?


This way:

class Location < AR::Base
  has_many :products
end

class Product < AR::Base
  belongs_to :location
end

You'd then set up a nested resource route:

resources :locations do
  resources :products
end

And when you're adding a location, you can add products to it with fields_for.


is it required to use nested_attributes_for in this scenario..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜