我有一个像例程和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在新的例程操作中,我为语言设置了RoutineConten字段。如果一个对象中的title是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插入到表中的emty对象后结束,为什么?我怎样才能禁用它?谢谢
发布于 2012-12-20 02:23:42
解决方案
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使用build方法。通过<<添加到数组这不是一个好主意
发布于 2012-12-20 02:14:06
在routine_contents表的routine_id中使用外键实现的has_many关联。
因此,在例程中添加新的RoutineContent需要在例程中确定主键才能写入routine_id,如果还没有保存,则会导致例程保存。
https://stackoverflow.com/questions/13958324
复制相似问题