2

我很难让 rails 4 与nested_attributes 一起工作并进行序列化。我有:

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

当我通过事件时:

{client_attributes: { phones: 'string'}}

它有效,但是当我尝试时

{client_attributes: { phones: [{phone_1_hash},{phone_2_hash}]}}

我收到“未经许可的参数:电话”消息并且字段未保存...

我试过用

class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [phones:[]])
  end
end

或者

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

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

4

1 回答 1

6

Pfff - 终于明白了......使用强参数没有未知键可以通过,所以这里的解决方案是:

class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [ {phones: [:number, :type]}])
  end
end

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

希望它可以帮助某人。

我可以在这里在我的可序列化字段中指定键,但是用户添加的键呢?序列化字段是否可用于强参数?(这可能应该是一个新问题......)

于 2013-08-22T12:37:08.223 回答