Save a JSON array to database in rails with strong_params

孤街醉人 提交于 2019-12-11 18:34:06

问题


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.

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.

How to fix? How do I get this JSON string through strong params?


回答1:


It's because signature is not inside the user attributes. 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">.



来源:https://stackoverflow.com/questions/30521054/save-a-json-array-to-database-in-rails-with-strong-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!