嵌套属性的批量分配错误

时间:2013-02-15 20:03:32

标签: ruby-on-rails nested-attributes mass-assignment

我有一个可以多次出现的事件(日期时间 - 不幸的是,我在代码中拼写错误)可以动态添加(感谢Ryan Bates的精彩教程:http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast):< / p>

has_many :occurances, :dependent => :destroy
accepts_nested_attributes_for :occurance, :reject_if => lambda { |a| a[:when].blank? }, :allow_destroy => true'

 attr_accessible :occurances, :occurances_attributes, :occurance_id

然后是表格:

.control-group.occurance_fields
  = f.label "Date & Time", :class => 'control-label'
  .controls
    = f.fields_for :occurance do |o_form|
      = o_form.text_field :when, :class => 'datepicker'

在event_controller的新方法中:

 @event.occurances.build

我提交表单时遇到问题:

Can't mass-assign protected attributes: occurance

如果我添加 attr_accessible :occurance,我会收到以下错误:

unknown attribute: occurance

我在这里缺少什么?我已经查看了一些有关类似问题的其他问题,但我无法将他们的解决方案转换为我的项目。

1 个答案:

答案 0 :(得分:0)

attr_accessible: occurance_ids

accepts_nested_attributes_for :occurances, :reject_if => lambda { |a| a[:when].blank? }, :allow_destroy => true'

编辑:

您:occurance_id在您的:attr_accessible中也无效。因为它是一个has_many关系,所以外键将在Occurances表中。