首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么编辑操作要尝试保存嵌套属性

为什么编辑操作要尝试保存嵌套属性
EN

Stack Overflow用户
提问于 2012-12-20 02:00:54
回答 2查看 76关注 0票数 1

我有一个像例程和RoutineContent这样的本地化模型

在Routine.rb中

代码语言:javascript
运行
复制
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中

代码语言:javascript
运行
复制
class RoutineContent < ActiveRecord::Base
  belongs_to :routine
  validates_presence_of :title
end

在新的例程操作中,我为语言设置了RoutineConten字段。如果一个对象中的title是emty,那么这个对象将被拒绝。

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

代码语言:javascript
运行
复制
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对象后结束,为什么?我怎样才能禁用它?谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-20 02:23:42

解决方案

代码语言:javascript
运行
复制
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方法。通过<<添加到数组这不是一个好主意

票数 1
EN

Stack Overflow用户

发布于 2012-12-20 02:14:06

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

因此,在例程中添加新的RoutineContent需要在例程中确定主键才能写入routine_id,如果还没有保存,则会导致例程保存。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13958324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档