繁体   English   中英

Rails-ActionController :: Parameters包含带有表单值的控制器值

[英]Rails - ActionController::Parameters include controller value with form values

我有一个会话变量(user_id),我想将其作为外键包含在用户要插入的记录中。 使用默认的params定义,我将所有表单值都通过表单提交到控制器的entity.update(params)方法。 该代码看起来像

 def brand_params
    @brand_params = params.require(:brand).permit(:name, :brand_type, :profile_id)
  end

更新方法看起来像

if @brand.update(brand_params)
        format.html { redirect_to @brand, notice: 'Widget was successfully updated.' }
        format.json { render :show, status: :ok, location: @brand }
      else
        format.html { render :edit }
        format.json { render json: @brand.errors, status: :unprocessable_entity }
      end

现在,我想将:profile_id会话变量附加到@brand_params并在这里跟随其他线程,我尝试了一个setter方法:

def set_brand_params(key, val)
    if @brand_params != nil
      @brand_params[key] = val
    end
  end

但是,将其命名为@brand_params始终为零。 尝试直接添加到brand_params哈希中不起作用,因为这是一种更好的方法。 如果有更好的方法来满足这个用例(我假设是常见的),我会很高兴! 否则,我想知道为什么var总是为零,尽管在这种情况下,至少brand_params方法将其视为已定义且具有值。 我在向服务器端的ActionController :: Parameters添加值中获得了此解决方案

这是请求的更新方法:

def update
    puts "update"
    set_brand_params("profile_id", session[:prof])
    respond_to do |format|
      if @brand.update(brand_params)
        format.html { redirect_to @brand, notice: 'Widget was successfully updated.' }
        format.json { render :show, status: :ok, location: @brand }
      else
        format.html { render :edit }
        format.json { render json: @brand.errors, status: :unprocessable_entity }
      end
    end
  end

我不同意将您的数据与参数合并。 因为您必须仅允许字段,所以您希望用户进行更新。 在这种情况下,您不希望用户更新品牌的profile_id ,这是安全性最佳做法。

然后brand_params必须为:

def brand_params
  @brand_params = params.require(:brand).permit(:name, :brand_type)
end

您的方法更新可能如下所示:

def update
  @brand = Brand.find(params[:id])
  @brand.assign_attributes(profile_id: session[:prof])
  respond_to do |format|
    if @barnd.update(brand_params)
      format.html { redirect_to @brand, notice: 'Widget was successfully updated.'}
      format.json { render :show, status: :ok, location: @brand }
    else
      format.html { render :edit }
      format.json { render json: @brand.errors, status: :unprocessable_entity }
    end
  end
end

您根本不需要方法set_brand_params

如果这样做不能解决问题,请发布入口控制器,希望我们能找到问题。

编辑:添加response_to。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM