简体   繁体   English

使用strong_params将JSON数组保存到Rails的数据库中

[英]Save a JSON array to database in rails with strong_params

I'm trying to update a users' attributes. 我正在尝试更新用户的属性。 All of the attributes are either strings or integers but I have one signature field which is a JSON object. 所有属性都是字符串或整数,但是我有一个签名字段,它是一个JSON对象。

Here are my params from the log: 这是日志中的参数:

 {"first_name"=>"Jackson", "last_name"=>"Cunningham", "email"=>"jackson@gmail.com", "phone"=>"", "address"=>"", "city"=>"", "province"=>""}, 
"signature"=>"[{\"lx\":80,\"ly\":4,\"mx\":80,\"my\":3},{\"lx\":78,\"ly\":3,\"mx\":80,\"my\":4},{\"lx\":72,\"ly\":4,\"mx\":78,\"my\":3},
{\"lx\":67,\"ly\":5,\"mx\":72,\"my\":4},{\"lx\":64,\"ly\":7,\"mx\":67,\"my\":5},
{\"lx\":60,\"ly\":9,\"mx\":64,\"my\":7},{\"lx\":51,\"ly\":13,\"mx\":60,\"my\":9},
{\"lx\":45,\"ly\":16,\"mx\":51,\"my\":13},
{\"lx\":41,\"ly\":19,\"mx\":45,\"my\":16},
{\"lx\":38,\"ly\":20,\"mx\":41,\"my\":19},
{\"lx\":39,\"ly\":20,\"mx\":38,\"my\":20},
{\"lx\":54,\"ly\":42,\"mx\":55,\"my\":42}]", 
    "commit"=>"Save", "id"=>"1"}

Update action and strong params method: 更新动作和强参数方法:

def update
    @user = current_user
    if @user.update_attributes(user_params)
      redirect_to dashboard_path
    else
      render :edit
    end
  end

  protected

  def user_params
    params.require(:user).permit(
        :first_name, :last_name, :phone, :email, :password_digest, :address, :city, :province, :signature)
  end

Everything is updating except the :signature, which is showing up in params[:signature] but not when I call user_params. 一切都在更新,除了:签名,这是表示PARAMS了[:签名]但不是当我打电话user_params。

How to fix? 怎么修? How do I get this JSON string through strong params? 如何通过强参数获取此JSON字符串?

It's because signature is not inside the user attributes. 这是因为signature不在用户属性内。 You have: 你有:

{
  "first_name" => "Jackson",
  "last_name" => "Cunningham",
  // etc.
},
"signature" => "asasfafsafs"

But what you actually want is: 但是,您真正想要的是:

{
  "first_name" => "Jackson",
  "last_name" => "Cunningham",
  "signature" => "asasfafsafs",
  // etc.
}

So in your HTML form, you should have something like <input name="user[signature]"> instead of <input name="signature"> . 因此,在您的HTML表单中,您应该使用<input name="user[signature]">而不是<input name="signature">

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

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