为什么我的表单可用于创建新对象而不是更新现有对象?
Why does my form work for creating new objects but not updating existing ones?
我想构建一个可以创建和更新我的模型的表单。我有这个
<%= form_for @vote, :url => votes_path, :remote => true do |f| %>
<%= f.hidden_field :person_id, :value => @person.id %>
<%= f.text_field :score %>
<%= f.submit %>
<%= submit_tag 'Skip', :name => 'skip', :type => 'button' %>
<% end %>
在我的路线文件中,我有
resources :votes
但是当“@vote”对象存在并且有ID时,上面的表单提交失败,报错
POST http://localhost:3000/votes 404 (Not Found)
以下是我的控制器的设置方式,尽管我觉得在尝试提交时它甚至还没有走那么远......
class Vote < ApplicationRecord
belongs_to :person
belongs_to :user
def create
puts "vote params; #{vote_params}"
@vote = Vote.new(vote_params)
...
private
def vote_params
params.require(:vote).permit(:score, :person_id)
end
如果您希望在您的模型上同时允许创建和更新方法 vote
,您可以跳过使用 url 并且 form_for 将自动检测 REST 调用。
<%= form_for @vote, :remote => true do |f| %>
<%= f.hidden_field :person_id, :value => @person.id %>
<%= f.text_field :score %>
<%= f.submit %>
<%= submit_tag 'Skip', :name => 'skip', :type => 'button' %>
<% end %>
现在要创建对象 vote
,您需要进行 POST 调用,例如
POST http://localhost:3000/votes
要更新对象,您需要进行 PUT/PATCH 调用,例如
PUT http://localhost:3000/votes/:id
我想构建一个可以创建和更新我的模型的表单。我有这个
<%= form_for @vote, :url => votes_path, :remote => true do |f| %>
<%= f.hidden_field :person_id, :value => @person.id %>
<%= f.text_field :score %>
<%= f.submit %>
<%= submit_tag 'Skip', :name => 'skip', :type => 'button' %>
<% end %>
在我的路线文件中,我有
resources :votes
但是当“@vote”对象存在并且有ID时,上面的表单提交失败,报错
POST http://localhost:3000/votes 404 (Not Found)
以下是我的控制器的设置方式,尽管我觉得在尝试提交时它甚至还没有走那么远......
class Vote < ApplicationRecord
belongs_to :person
belongs_to :user
def create
puts "vote params; #{vote_params}"
@vote = Vote.new(vote_params)
...
private
def vote_params
params.require(:vote).permit(:score, :person_id)
end
如果您希望在您的模型上同时允许创建和更新方法 vote
,您可以跳过使用 url 并且 form_for 将自动检测 REST 调用。
<%= form_for @vote, :remote => true do |f| %>
<%= f.hidden_field :person_id, :value => @person.id %>
<%= f.text_field :score %>
<%= f.submit %>
<%= submit_tag 'Skip', :name => 'skip', :type => 'button' %>
<% end %>
现在要创建对象 vote
,您需要进行 POST 调用,例如
POST http://localhost:3000/votes
要更新对象,您需要进行 PUT/PATCH 调用,例如
PUT http://localhost:3000/votes/:id