嵌套 has_one 关联的强参数 [英] Strong Parameters for Nested has_one Association

查看:41
本文介绍了嵌套 has_one 关联的强参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎遗漏了一些明显的东西,但我无法允许嵌套 has_one 关联的属性.

I seem to be missing something obvious, but I am unable to permit the attributes for a nested has_one association.

def create
  @crossword = Crossword.new(crossword_params)

  if @crossword.save
    render :show, status: :created, location: [:api, @crossword]
  else
    render json: @crossword.errors, status: :unprocessable_entity 
  end
end

def crossword_params
  params.require(:crossword).permit(:title, :grid_size, grid_size_attributes: [:rows, :columns])
end

型号:

validates :title, :grid_size, presence: true
validates_associated :grid_size
has_one :grid_size
accepts_nested_attributes_for :grid_size

请求:

POST /api/crosswords.json HTTP/1.1
X-Accept: application/crosswords.v1
Content-Type: application/json
Host: localhost:3000
Connection: close
User-Agent: Paw/2.1 (Macintosh; OS X/10.10.0) GCDHTTPRequest
Content-Length: 83

{"crossword":{"title":"My Aweosme Crossword","grid_size":{"rows":15,"columns":15}}}

Rails 控制台输出:

Started POST "/api/crosswords.json" for 127.0.0.1 at 2014-12-19 11:05:13 -0500
Processing by Api::V1::CrosswordsController#create as JSON
Parameters: {"crossword"=>{"title"=>"My Aweosme Crossword", "grid_size"=>{"rows"=>15, "columns"=>15}}}
Can't verify CSRF token authenticity
Unpermitted parameters: grid_size
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
Completed 422 Unprocessable Entity in 2ms (Views: 0.1ms | ActiveRecord: 0.2ms)

我是否遗漏了一些微不足道的东西?这似乎是每个人都说要做的.

Am I missing something trivial? This seems to be how everyone is saying to do it.

推荐答案

将 POST 正文中的grid_size"更改为grid_size_attributes".

Change "grid_size" to "grid_size_attributes" in your POST body.

如果您想继续使用grid_size",请更新您的crossword_params 方法:

If you want to continue to use "grid_size", update your crossword_params method:

def crossword_params
    params[:crossword][:grid_size_attributes] = params[:crossword][:grid_size] if params[:crossword][:grid_size]
    # NOTE :grid_size removed!
    params.require(:crossword).permit(:title, grid_size_attributes: [:rows, :columns])
end

这篇关于嵌套 has_one 关联的强参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆