Search code examples
ruby-on-railsjsonstrong-parameters

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.

Here are my params from the log:

 {"first_name"=>"Jackson", "last_name"=>"Cunningham", "email"=>"[email protected]", "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?


Solution

  • 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">.