在使用 if 语句更新之前覆盖用户表单中的 POST 值
Override POST value from user form before update with if statement
我有一个工作正常的表格:
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 字段时,代码在保存之前似乎没有抓住 params[: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
我有一个工作正常的表格:
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 字段时,代码在保存之前似乎没有抓住 params[: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