如何使rails strong_parameters + nested_attributes + serialize工作?

san*_*xus 2 serialization nested-attributes strong-parameters ruby-on-rails-4

我很难让rails 4使用nested_attributes和serialize.我有:

class Client < ActiveRecord::Base
  belongs_to :event
  serialize :phones
end


class Event < ActiveRecord::Base
  has_one :client
end


class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [:phones])
  end
end
Run Code Online (Sandbox Code Playgroud)

当我通过活动时:

{client_attributes: { phones: 'string'}}
Run Code Online (Sandbox Code Playgroud)

它有效,但当我尝试

{client_attributes: { phones: [{phone_1_hash},{phone_2_hash}]}}
Run Code Online (Sandbox Code Playgroud)

我收到'未经许可的参数:手机'消息并且字段未保存...

我试过用

class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [phones:[]])
  end
end
Run Code Online (Sandbox Code Playgroud)

要么

class Client < ActiveRecord::Base
  belongs_to :event
  serialize :phones, Array
end
Run Code Online (Sandbox Code Playgroud)

但到目前为止没有任何帮助 任何建议,将不胜感激.谢谢!

san*_*xus 6

Pfff - 终于搞定了......有了强参数,没有未知密钥可以通过,所以这里的解决方案是:

class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [ {phones: [:number, :type]}])
  end
end
Run Code Online (Sandbox Code Playgroud)

基于http://edgeapi.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit-21

希望它可以帮助某人.

我可以在我的serialisable字段中指定密钥,但是用户添加密钥的是什么?序列化字段是否可以使用强参数?(这可能应该是一个新问题...)