为什么编辑动作尝试保存嵌套属性

时间:2012-12-19 18:00:54

标签: ruby-on-rails nested-attributes

我有一个像Routine和RoutineContent这样的模型用于本地化
在Routine.rb

Class Routine < ActiveRecord::Base
  has_many :routine_contents, dependent: :destroy
  accepts_nested_attributes_for :routine_contents, reject_if: proc {|attributes| attributes['title'].empty?}
end

和RoutinesContent

class RoutineContent < ActiveRecord::Base
  belongs_to :routine
  validates_presence_of :title
end

在新的Routine操作中,我为语言提供了RoutineConten字段。如果一个对象中的标题是emty,则该对象将被拒绝。

当我去编辑动作时,我会这样做

def set_routine_contents
    contents = @routine.routine_contents.group_by {|content| content.lang}
    if contents['ru'].nil?
      @routine.routine_contents << RoutineContent.new(lang: 'ru')
    end
    if contents['en'].nil?
      @routine.routine_contents << RoutineContent.new(lang: 'en')
    end
end

在表中的这个Rails INSERT INTO emty对象之后结束,为什么?我怎么能禁用它? 感谢

2 个答案:

答案 0 :(得分:1)

<强>解决方案

def set_routine_contents
    contents = @routine.routine_contents.group_by {|content| content.lang}
    if contents['ru'].nil?
      @routine.routine_contents.build(lang: 'ru')
    end
    if contents['en'].nil?
      @routine.routine_contents.build(lang: 'en')
    end
end

使用构建方法。通过&lt;&lt;添加到阵列这是个坏主意

答案 1 :(得分:0)

has_many关联使用routine_id routine_contents表中的外键实现。

因此,在您的例程中添加新的RoutineContent需要在例程中确定要写入routine_id的主键,并在未保存的情况下导致例程保存。