1

I have a many_to_many relation with photos and sponsors.

When creating a new Photo, in the new.html.erb view, I would like to add the sponsor attributes (which belong to a different model, but are relationed with photo), but I don't know how to.

I want to add :sponsor_name, :sponsor_web inputs in the Photo creation view, so I can add info about the sponsors the photo has when I create a new photo

I tried creating 2 simple_forms in the same view, one with the photo table attributes, and the other with the sponsor attributes, but didn't work.

Mi view (new.html.erb)

<%= simple_form_for [current_user, @photo] do |f| %>
                    <%= f.button :submit, "Subir Spot"%>
            <% end %>

My Photos#new Controller

def new
    @photo = Photo.new
    @sponsor = @photo.sponsors
end
2
  • Be careful, you are mixing singular and plural names for the same things. If you want to create or update multiple objects within one form, see nested_attributes. Commented Sep 9, 2014 at 10:31
  • Ok thank you, just looked at that. But, how about those nested attributes? Should I add them as well as strong parameters in Photos Controller? Thanks! Commented Sep 9, 2014 at 10:40

1 Answer 1

2

Nested

You'll want to use accepts_nested_attributes_for in your Photo model:

#app/models/photo.rb
class Photo < ActiveRecord::Base
   has_many :sponsors
   accepts_nested_attributes_for :sponsors
end

This gives you the ability to use a nested form:

#app/controllers/photos_controller.rb
class PhotosController < ApplicationController
   def new
       @photo = Photo.new
       @photo.sponsors.build
   end

   def create
       @photo = Photo.new photo_params
       @photo.save
   end

   private

   def photo_params
      params.require(:photo).permit(:photo, :params, sponsors_attributes: [:name, :web])
   end
end

#app/views/photos/new.html.erb
<%= form_for @photo do |f| %>
   # Photo attributes here
   <%= f.fields_for :sponsors do |s| %>
      <%= s.text_field :name %>
      <%= s.text_field :web %>
   <% end %>
   <%= f.submit %>
<% end %>

This will work to create a new Sponsor object when you make a new Photo object, thus providing you with the ability to pass nested data.

--

Although this will work for a has_many :through association, you'll want to be careful when using it with has_and_belongs_to_many, as if you just wanted to associate two models, you'll be better populating the [other]_ids method of your new Photo object

I can detail this if you want more information

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

1 Comment

Just worked out of the box. Understood perfectly. Thanks so much

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.