Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在使用if语句更新之前覆盖用户表单中的POST值_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

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]
谢谢您!