开发者

How to create only the field_for object in a nested form

I have a nested form where users can create any amount of products (<%= f.fields_for :products d开发者_开发技巧o |product| %>) and at the same time also create a location (nested_form_for @location) to put those products. But instead, what i want is users to select a location and only be allowed to create the products. I don't want to create the locations at all on this form. The form also should not give a location per product but only one location for all of them.

How would you make the form select a location and create products only ?

This form creates both the location and X amount of products:

<%= nested_form_for @location, :validate => true  do |f| %>
      # This will turn into selecting of predefined locations and not creating
      # the location as you see below this line
    <%= f.label :business_name, "Business Name" %><br />
    <%= f.text_field :business_name %>

    <%= f.label :address %><br />
    <%= f.text_field :address %>

    <%= f.label :phone_number, "Phone Number" %><br />
    <%= f.text_field :phone_number %>

    <%= f.label :website %><br />
    <%= f.text_field :website %>
  </div>

  <%= f.fields_for :products do |product| %>
        <%= product.label :name %>:<br>
        <%= product.text_field :name %> 

        <%= product.label :price %>:<br>
        <%= product.text_field :price %>

    <%= product.link_to_remove "Remove" %> # Removes a product field

  <% end %>
  </div>
  <p><%= f.link_to_add "Add Product", :products %></p> # Ajax add product field

    <div class="actions">
       <%= f.submit %>
    </div>
<% end %>


If I understand you correctly, you want users to choose from a list of locations, and then add products to that location. These locations are predefined somewhere (I'm getting in your db_seed) in your application. Assuming those two things, then the question to your answer is just have a normal form_for @product and inside your form you will have a select with the option objects being the location where they users can choose.

<%= form_for @product do |p| %>
    <%= p.label :name %>:<br>
    <%= p.text_field :name %> 

    <%= p.label :price %>:<br>
    <%= p.text_field :price %>

    <%= select :product, :location_id, Location.all.collect {|l| [ l.business_name, l.id ] } %>
<% end %>

and in your controller you can just get the location with params[:product][:location_id] to retrieve the location the user selected and do your normal database stuff. Hopefully that's clear enough for you.

If you want to create more than one product at a time, you need to use a form_tag and generate your own helpers to add/remove products. This is more difficult but creates a better user experience.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜