0

A product has many images. I am creating a form that only edits the images of a product.

Here is what I have so far:

<%= form_for(@product, :html => { :multipart => true }) do |f| %>
  <%= f.fields_for :images do |i| %>

  <% end %>
<% end %>

Is this portion correct?

I need a radio button and file field for each image, how can I do this for each image?

Also this form is only for editing the images not creating them.

2 Answers 2

1

I am assuming that your Product model has the following association:

has_many :images

To solve your problem you'll need to look at forms with nested models. Add the following line to your Product model, it will allow you to modify nested models within the parent model form.

accepts_nested_attributes_for :images

Modify your form:

<%= f.fields_for :images do |i| %>
 i.radio_button_tag :field_name
 f.file_field :file
<% end %>

Do not forget to add images_attributes hash with images fields to list of permitted attributes for mass assignment and you should be good to go!

This railscast might be very handy. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you have an arbitrary number of images, you're probably better off creating a separate model in your application (call it Images for this example). Then you can define a many to one relation between Products and Images. The rails guide on active record associations has some good examples for how to set up a has_many relation.

To answer your question, after you have the relationships for your models in place, you're better off using nested forms. There's an old railscast episode that shows how to do this, or a newer updated one if you have a railscast membership.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.