简体   繁体   English

从控制器参数保存Rails模型?

[英]Save Rails model from controller params?

I tried User.create(params), but this says that "controller" and "action" aren't mass assignable. 我尝试过User.create(params),但这说“控制器”和“动作”不是可分配的。 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. 一些例子似乎表明我可以使用params [:user],但如果我希望帖子只是用户对象,则params [:user]看起来像是零。

So I'm posting with {username: 'blah', password: 'blah'}, and username and password are in the params, but not params[:user]. 所以我发布了{username:'blah',密码:'blah'},用户名和密码都在params中,但不是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): 在Rails项目中有一个约定,其中表单元素以某种方式命名(使用表单帮助程序自动为您执行此操作):

<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哈希:

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. 由于路由的工作方式,控制器,操作,id(如果适用)或任何自定义路由部分的键值对将添加到此params散列中。

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

If params[:user] is nil for you, you may need to change your form to match the convention. 如果params[:user]对你来说是零,则可能需要更改表单以符合约定。

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

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

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