Rails 表单未将输入保存到数据库

Dea*_*ear 2 ruby database forms ruby-on-rails

我制作了一个非常简单的 RESTful 应用程序,当我在表单字段中输入一个字符串并提交时,数据库保存 NULL 而不是输入字符串。

这是我的控制器:

def create
  @song = Song.create(params[:title])
  flash[:success] = "You have successfully created a new project!"
  redirect_to "/songs/#{@song.id}"
end
Run Code Online (Sandbox Code Playgroud)

这是我在 new.html.erb 文件中的表单:

<%= form_for(@song) do |f| %>

<div class="field">
  <%= f.label :title %><br>
  <%= f.text_field :title %>
</div>

<div class="actions">
  <%= f.submit %>
</div>

<br>

<% end %>
Run Code Online (Sandbox Code Playgroud)

Man*_*eep 5

如果你使用的是rails < 4那么你应该有

def create
  @song = Song.create(params[:song])
  flash[:success] = "You have successfully created a new project!"
  redirect_to @song
end 
Run Code Online (Sandbox Code Playgroud)

如果你使用的是rails > 4那么你应该有

def create
  @song = Song.create(song_params)
  flash[:success] = "You have successfully created a new project!"
  redirect_to @song
end

private
def song_params
  params.require(:song).permit(:title)
end
Run Code Online (Sandbox Code Playgroud)

  • @Iceman @Mandeep 我在routes.rb 文件中添加了`resources :songs`,现在它可以工作了。 (2认同)