GangstaGraham
GangstaGraham

Reputation: 9355

Rails - Object Not Getting Created From 'New' Form

I am new to Rails, can you check my code to see where I might be going wrong. I am attempting to create a Song object.

By looking at my SQLite File, I can see that no new songs are being created.

In views/songs/new.html.erb

<!DOCTYPE html>
<html>
    <head>
      <title>MusicDiscoveryApp</title>
      <%= stylesheet_link_tag    "application", :media => "all" %>
      <%= javascript_include_tag "application" %>
      <%= csrf_meta_tags %>
    </head>
    <body>
          <%= form_for(@song, :html => {:id => 'add-to-library', :method => :post}) do |f| %>
            <div class="item-info">
              <%= f.select :category_id, [['Pop', 1], ['Rock', 2], ['Rap', 3], ['Reggae', 4], ['Other', 5]] , {:prompt=>"Select A Category"}, :id=>"choose-category"%>
            </div>
              <div class="item-info">
                <%= f.text_field :name , :placeholder=>"Song Name"%>
            </div>
            <div class="item-info">
              <%= f.text_field :price, :placeholder=>"Price"%>
            </div>
              <div class="item-info">
                <%= f.text_area :details ,:placeholder=>"Details"%>
            </div>
            <div class="item-actions">
              <%= f.submit "Post to Songs Library", :class=>"add-song"%>
            </div>
          <% end %>
    </body>
</html>

The 'new' method from songs_controller.rb - it was automatically generated

  def new
    @song = Song.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @song }
    end
  end

The 'create' method from songs_controller.rb - also automatically generated

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

Thanks for your time, I hope you can explain to me what I did wrong here. Thanks once again.

Upvotes: 0

Views: 207

Answers (1)

BigLoppy
BigLoppy

Reputation: 126

The song isn't being saved. Add:

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

to your controller create method or change new to create

@song = Song.create(params[:song])

Upvotes: 2

Related Questions