beastlyCoder
beastlyCoder

Reputation: 2401

Nested Attributes Rails

How am I able to create a link that says something like "Add more fields" within my song model? I was able to do it with nested attributes for my events has_many songs relationship. Would I need to do the same just for songs?

Here is the song page that handles with new song creation while selecting which event to add songs to:

<br>
<br>
<div class ="container">
  <div class="jumbotron">
    <h2> Select an event to add songs to: </h2>
    <%= form_for @song do |f| %>


      <%= f.collection_select(:event_id, Event.all, :id, :name) %>

      <h3> Enter your song </h3>
      <%= f.text_field :artist, placeholder: "Artist" %>
      <%= f.text_field :title,  placeholder: "Title" %>
      <%= f.text_field :genre,  placeholder: "Genre" %>
      <h2> Enter the partycode for that event: </h2>

      <%= form_for Event.new do |f| %>

      <%= f.text_field :partycode, :required => 'required'%>

      <%= f.submit "Submit", class: "btn btn-primary", :onclick => "window.alert('Aye');" %>
      <% end %>

      <h2><%= link_to_add_fields "Want to add more songs?", f, :songs %> </h2>
    <% end %>
  </div>
</div>

The link_to_add_fields is defined here in the ApplicationHelper file:

module ApplicationHelper
  def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render("songs_fields", f: builder)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
  end
end

I am getting an error here that says in this ApplicationHelper file that says: enter image description here

Upvotes: 0

Views: 46

Answers (2)

coreyward
coreyward

Reputation: 80041

It looks like you've gotten caught up in the relationship between Events and Songs. You start out defining a form to create/edit a Song, provide an interface for selecting an Event, and within the same form offer to “Add a Song” (to a song).

Note that this is reflected in your description of this page: “the song page that handles with new song creation while selecting which event to add songs to”. You would do well to read that out loud, then figure out what you want this page to do.

As for the error you're getting: the result of your error is that Song doesn't have a songs method. In the scope of your link_to_add_fields method, f is the form helper. Calling f.object returns the object that you passed into the form_for method, in this case represented by @song. The association you passed to link_to_add_fields, :songs, doesn't exist as an association of Song. Which is to say that you can't call @song.songs.

Upvotes: 1

Sajjad Murtaza
Sajjad Murtaza

Reputation: 1504

You can try cocoon gem.

Cocoon makes it easier to handle nested forms.

Upvotes: 0

Related Questions