简体   繁体   中英

Save Rails model from controller params?

I tried User.create(params), but this says that "controller" and "action" aren't mass assignable. I could exclude these properties, but is there an easier way to marshall to the properties I need?

Some examples seem to indicate I can use params[:user], but if I want the post to be just the user object, params[:user] looks like it's nil.

So I'm posting with {username: 'blah', password: 'blah'}, and username and password are in the params, but not params[:user].

class UsersController < ApplicationController
  def create
    user = User.create(params[:user])
    if user.save
      render :json => user, :status => :created
    else
      logger.error user.errors
      render :json => {:status => :error, :errors => user.errors}, :status => :bad_request
    end
  end
end

There is a convention in Rails projects, where form elements are named in a certain way (using the form helpers does this for you automatically):

<input type='text' name='user[username]'>
<input type='text' name='user[username]'>

When they are posted to the controller, these are converted to the params hash:

params = {
  :user => {
    :username => 'whatever',
    :password => 'somepass'
  }
}

Because of the way the routing works, key-value pairs for the controller, action, id (if applicable) or any custom route parts are added to this params hash.

params.merge!({
  :controller => 'users',
  :action     => 'create'
})

If params[:user] is nil for you, you may need to change your form to match the convention.

尝试User.create(request.request_parameters)User.create(JSON.parse(request.body.read))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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