john doe
john doe

Reputation: 9660

Rails Action to Accept JSON as Input, Convert JSON to Object and Then Save

I have a simple new form like this:

<h1> New </h1>

<%= form_for :user, url: 'create' do |f| %>

    <p>
    <%= f.label :firstName %>   
    <%= f.text_field :firstName %>
    </p>

    <p>
    <%= f.label :lastName %>    
    <%= f.text_field :lastName %>
    </p>

    <p>
    <%= f.label :userName %>    
    <%= f.text_field :userName %>
    </p>

    <p>
    <%= f.label :password %>    
    <%= f.text_field :password %>
    </p>

    <p>
    <%= f.label :email %>   
    <%= f.text_field :email %>
    </p>

    <p>
        <%= f.submit %>
    </p>

<% end %>

As you can see it invokes the create action which is defined below:

def create  
    @user = User.new(params[:user])
    @user.save
  end 

It gives me the following error:

ActiveModel::ForbiddenAttributesError

Extracted source (around line #8):
6
7
8
9
10
11

  def create 

    @user = User.new(params[:user])
    @user.save

  end 

All I want is that my method create accept input as json arguments and then convert those arguments to a user object and then save the object.

UPDATE:

I have the following create method which is defined as post:

def create  
  @user = User.new(user_params)   
  @user.save  
  end 

I am sending the following json but it never gets saved:

{"firstName":"John", "lastName:"Doe", "userName":"johndoe", "password":"mypassword", "email":"[email protected]"}

UPDATE:

After passing the following JSON:

{"user":{"firstName":"John", "lastName:"Doe", "userName":"johndoe", "password":"mypassword", "email":"[email protected]"}}

I get the following error in my HTTPClient application:

<h2>795: unexpected token at &#39;{&quot;user&quot;:{&quot;firstName&quot;:&quot;John&quot;, &quot;lastName:&quot;Doe&quot;, &quot;userName&quot;:&quot;johndoe&quot;, &quot;password&quot;:&quot;mypassword&quot;, &quot;email&quot;:&quot;[email protected]&quot;}}&#39;</h2>

UPDATE:

Now I get the following error after I got the JSON correct:

ActionController::InvalidAuthenticityToken in UsersController#create

Upvotes: 1

Views: 2157

Answers (1)

jvperrin
jvperrin

Reputation: 3368

The error you are encountering is from Strong Parameters, which is included in Rails by default for Rails 4. Try using the following code in your controller instead to allow only certain parameters:

def create
  @user = User.new(user_params)
  @user.save

  respond_to do |format|
    format.json { render :json => @user }
  end
end

private

  def user_params
    params.require(:user).permit(:firstName, :lastName, :userName, :password, :email)
  end

Upvotes: 1

Related Questions