TangoKilo
TangoKilo

Reputation: 1795

Rails Submit Button doesn't do anything on click after nested form added

I'm trying to use a nested form at the moment to add category tags to a song as you create the song. The form was working fine until I added the nested attributes to it, and now the submit button doesn't do anything when you click on it (the page doesn't reload or anything).

In my model a song has many categories though categorizations, and vice versa.

Here's the form:

  <div class="span10 offset1">
    <%= form_for(@song) do |f| %>

      <%= f.label :title, "Title" %>
      <%= f.text_field :title %>

      <%= nested_form_for(@song.categorizations.build) do |f| %>
        <%= f.label :category_id, "TAG" %>
        <%= f.select :category_id, options_for_select(Category.all.collect {|c| [ c.tag, c.id ] }, { :include_blank => true }), prompt: "" %>
      <%end%>

      <%= f.submit "Save song", class: "btn btn-large btn-primary" %>
    <% end %>
  </div> 

And my controller for songs:

  def new
    @song = Song.new
  end

 def create
    @song = Song.new(params[:song])
    if @song.save

        flash[:success] = "Song successfully added to library"
        redirect_to @song
    else
        #FAIL!
        render 'new'
    end
  end

The Categorization controller:

def new
    @categorization = Categorization.new
  end

  def create
    @song = Song.find(params[:id])
    @categorization = Category.new(params[:categorization])
    if @categorization.save
        flash[:success] = "Tag added!"
        redirect_to song_path(@song)
    else
        flash[:fail] = "TAG ERROR"
        redirect_to edit_song_path(@song)
    end
  end

Thank you in advance for any help!

Upvotes: 0

Views: 1835

Answers (1)

Nate914375
Nate914375

Reputation: 192

The outer form is the one that's should be a nested_form_for, not the inner part, which should be fields_for.
Also, you probably shouldn't name both of them f, to avoid confusion (though I think it wont stop it from working).

<div class="span10 offset1">
<%= nested_form_for(@song) do |f| %>

  <%= f.label :title, "Title" %>
  <%= f.text_field :title %>

  <%= f.fields_for(@song.categorizations.build) do |catsf| %>
    <%= catsf.label :category_id, "TAG" %>
    <%= catsf.select :category_id, options_for_select(Category.all.collect {|c| [ c.tag, c.id ] }, { :include_blank => true }), prompt: "" %>
  <%end%>

  <%= f.submit "Save song", class: "btn btn-large btn-primary" %>
<% end %>

Upvotes: 1

Related Questions