【问题标题】:Rails form is not saving input to the databaseRails 表单未将输入保存到数据库
【发布时间】:2014-08-20 02:57:42
【问题描述】:

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

这是我的控制器:

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

这是我在 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 %>

【问题讨论】:

  • 我觉得应该是Song.create(params[:song])

标签: ruby-on-rails ruby database forms


【解决方案1】:

如果你使用 rails 那么你应该有

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

如果你使用的是 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

【讨论】:

  • 如果路线发生变化,使用redirect_to "/songs/#{@song.id}" 不是最好的方法。最好使用redirect_to @song
  • @Dear1ofGdBear 如果您更改您的 routes.rb 此链接可能会停止工作。最好让 Rails 找出当前路线。 guides.rubyonrails.org/routing.html
  • @Dear1ofGdBear 这是一个单独的问题,并确保将您的 routes.rb 文件放在您的问题中:)
  • 你的 routes.rb 是什么样的?您需要一行 resources :songs 才能正常工作
  • @Iceman @Mandeep 我在 routes.rb 文件中添加了 resources :songs 现在可以使用了。
猜你喜欢
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
相关资源
最近更新 更多