2013-06-27 45 views
0

我是Rails的新手,你能檢查我的代碼,看看我可能會出錯的地方。我正在嘗試創建一個Song對象。Rails - 對象沒有從'新'形式創建形式

通過查看我的SQLite文件,我可以看到沒有新的歌曲正在創建。

在視圖/歌曲/ 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> 

從songs_controller.rb '新' 方法 - 它是自動生成的

def new 
    @song = Song.new 

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

從songs_controller的 'create' 方法。 rb - 也自動生成

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

謝謝你的時間,我希望你能向我解釋wha我在這裏做錯了。再次感謝。

+0

'ActiveRecord'的'new'法新記錄不保存到數據庫中。 –

+0

@AlexWayne只是好奇,爲什麼不呢?是否有沒有保存對象的新實例的用例? – GangstaGraham

+0

因爲你想在保存它們之前在內存中創建對象,給你一個操縱它的機會,也許它不會通過驗證,各種原因。看看你的'new'控制器動作,它使表單的一個對象呈現屬性。你不想保存它,因爲它還沒有數據。 –

回答

2

歌曲沒有被保存。地址:

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

到控制器的方法創建或更改新創建

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