Ruby on rails 与x27之间的差异;保存';和';更新';用于不同的http请求
当我尝试用下面的代码中的Ruby on rails 与x27之间的差异;保存';和';更新';用于不同的http请求,ruby-on-rails,Ruby On Rails,当我尝试用下面的代码中的@post.save替换@post.update时,它仍然有效,并且返回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 de
@post.save
替换@post.update
时,它仍然有效,并且返回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
以下是我的耙子路线:
$ 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
为什么它没有更新或覆盖我的记录
对相同的方法使用不同的http请求会对它们产生影响吗?当使用正确的语法传递时,是否可以使用PUT
、GET
、PATCH
和DELETE
进行保存
第一个问题是关于rails 4指南。[1]提供了一个很好的解释
保存(*)链接
保存模型
如果模型是新的,则会在数据库中创建一条记录,否则会更新现有记录。
默认情况下,保存始终运行验证。如果其中任何一个失败,操作将被取消,并且save返回false。但是,如果您提供validate:false,则会完全忽略验证
保存!(*)链接
保存模型
如果模型是新的,则会在数据库中创建一条记录,否则会更新现有记录
救命啊!验证始终运行。如果其中任何一个失败,将引发ActiveRecord::RecordInvalid
更新(属性)链接
从传入的散列更新模型的属性,并保存记录,所有记录都包装在事务中。如果对象无效,保存将失败,并返回false。
另别名为:更新_属性
更新!(属性)链接
更新其接收器,就像更新一样,但会调用save!而不是保存,因此如果记录无效,将引发异常。
别名为:更新_属性 因为
save
不接受属性作为参数<代码>保存只能接受像验证:false这样的参数来跳过验证
如果要使用保存
,则需要在保存
之前分配或修改各个属性。但是,如果您想要批量分配,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
准确地说:1。Save将保存可能不需要的类的所有实例。尤其是当验证存在时。
e、 g@post.save
它将更新post的所有属性或列
Update将只更新类的单个属性或该特定类的相应模型
@更新后(:状态,当前)
“当我试着用@post.save替换@post.update时”,你是说你在更新操作中的代码是这样的@post.save(post_参数)
?写更新属性而不是更新。是的,我忽略了这个部分,就像我是新手一样。谢谢你的回答,我忽略了那个部分。我的一般问题是,对相同的方法使用不同的http请求是否会对它们产生任何影响?或者例如:当使用正确的语法传递时,我们可以使用PUT、GET、PATCH和DELETE进行保存吗?不…save
和updates
不知道请求头,无论您发出何种请求,它们的过程都是相同的