Ruby on rails 在使用if语句更新之前覆盖用户表单中的POST值
我有一个完美的表格:Ruby on rails 在使用if语句更新之前覆盖用户表单中的POST值,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有一个完美的表格: def update @post = Post.find(params[:id]) if @post.update_attributes(post_params) flash[:notice] = 'Blog post updated.' redirect_to(:action => 'index') else render("edit") end end 但是如果用户在提交前将表单留空,那么我想传入一个变量。
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
flash[:notice] = 'Blog post updated.'
redirect_to(:action => 'index')
else
render("edit")
end
end
但是如果用户在提交前将表单留空,那么我想传入一个变量。否则,将存储用户提交的值。我不能完全理解语法,我需要这样的东西:
def update
if params[:permalink] == nil
params[:permalink] = "#{defaultValue}"
end
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
flash[:notice] = 'Blog post updated.'
redirect_to(:action => 'index')
else
render("edit")
end
end
当表单中实际上有一个:permalink字段时,代码在保存之前似乎没有抓住
参数[:permalink]
。有什么建议吗?解决方案:
def update
if !params[:post][:permalink].presence
params[:post][:permalink] = "#{defaultValue}"
end
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
flash[:notice] = 'Blog post updated.'
redirect_to(:action => 'index')
else
render("edit")
end
end
params[:permalink]
很可能是一个空字符串,而不是nil。尝试使用params[:permalink]=params[:permalink].presence | | defaultValue
更改整个if块,因为您正在尝试保存post_params
可能您有params[:post][:permalink]
而不是params[:permalink]
谢谢您!