当我在下面的代码中尝试替换@post.update时@post.save,它仍然有效并返回true,但值未更新.
def create
@post = Post.new(post_params)
if @post.save
redirect_to posts_path, notice: 'Post was successfully created.'
else
render action: 'new'
end
end
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
Run Code Online (Sandbox Code Playgroud)
以下是我的佣金路线:
$ rake routes
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root / welcome#index
Run Code Online (Sandbox Code Playgroud)
为什么不更新或覆盖我的记录?
对相同方法使用不同的http请求会对它们产生任何影响吗?当使用正确的语法传递时,我们可以使用PUT,和保存吗?GETPATCHDELETE
关于导轨4导轨的问题,第一个指南.
Siv*_*iva 21
因为save不会接受属性作为参数; save只能接受validate: false跳过验证等参数.
如果要使用save,则需要先分配或修改单个属性save.但如果你想要大规模分配,那update将是你的选择.
@post.f_name = 'foo'
@post.l_name = 'bar'
@post.update # This will not work
@post.save # This will work
@post.save({:f_name=>"peter",:l_name=>"parker"}) # This will not work
@post.update({:f_name=>"peter",:l_name=>"parker"}) # This will work
Run Code Online (Sandbox Code Playgroud)
[1] http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html提供了一个很好的解释.
保存(*)链接
保存模型.
如果模型是新的,则在数据库中创建记录,否则现有记录将更新.
默认情况下,保存始终运行验证.如果其中任何一个失败,则取消操作并保存返回false.但是,如果您提供validate:false,则会完全绕过验证.
保存!(*)链接
保存模型.
如果模型是新的,则在数据库中创建记录,否则现有记录将更新.
随着保存!验证总是运行.如果其中任何一个失败,则会引发ActiveRecord :: RecordInvalid.
更新(属性)链接
从传入的哈希更新模型的属性并保存记录,所有记录都包含在事务中.如果对象无效,则保存将失败并返回false.别名为:update_attributes
更新!(属性)链接
更新其接收器就像更新但呼叫保存!而不是保存,因此如果记录无效,则会引发异常.别名为:update_attributes!
| 归档时间: |
|
| 查看次数: |
15970 次 |
| 最近记录: |