Ruby on rails RubyonRails:在创建其父级时使用默认值构建子级
我有一个父母和孩子的模型关系。在子模型的migration.rb中,子模型的每个列都有默认值(除了parent_id列) 当我创建一个新的父对象时,我如何创建它,以便创建一个子对象并将其与来自默认值的数据以及父对象id一起保存到表中Ruby on rails RubyonRails:在创建其父级时使用默认值构建子级,ruby-on-rails,parent-child,Ruby On Rails,Parent Child,我有一个父母和孩子的模型关系。在子模型的migration.rb中,子模型的每个列都有默认值(除了parent_id列) 当我创建一个新的父对象时,我如何创建它,以便创建一个子对象并将其与来自默认值的数据以及父对象id一起保存到表中 我认为这与在父模型上创建之后的有关,但我不确定如何设置它。修订:我修订了答案,以便在创建和构建(而不是创建)关联模型之前使用。一旦父模型被保存,ActiveRecord机器就会负责保存关联的模型 我甚至测试了这个代码 # in your Room model...
我认为这与在父模型上创建之后的
有关,但我不确定如何设置它。修订:我修订了答案,以便在创建和构建(而不是创建)关联模型之前使用。一旦父模型被保存,ActiveRecord机器就会负责保存关联的模型
我甚至测试了这个代码
# in your Room model...
has_many :doors
before_create :build_main_door
private
def build_main_door
# Build main door instance. Will use default params. One param (:main) is
# set explicitly. The foreign key to the owning Room model is set
doors.build(:main => true)
true # Always return true in callbacks as the normal 'continue' state
end
####### has_one case:
# in your Room model...
has_one :door
before_create :build_main_door
private
def build_main_door
# Build main door instance. Will use default params. One param (:main) is
# set explicitly. The foreign key to the owning Room model is set
build_door(:main => true)
true # Always return true in callbacks as the normal 'continue' state
end
添加
构建方法由拥有模型的机器通过has_many语句添加。由于该示例使用的has_many:doors(模型名Door),因此构建调用是doors.build
请参阅和,以查看添加的所有其他方法
# If the owning model has
has_many :user_infos # note: use plural form
# then use
user_infos.build(...) # note: use plural form
# If the owning model has
has_one :user_info # note: use singular form
# then use
build_user_info(...) # note: different form of build is added by has_one since
# has_one refers to a single object, not to an
# array-like object (eg user_infos) that can be
# augmented with a build method
Rails 2.x为关联引入了autosave选项。我认为它不适用于上述情况(我使用默认设置) 你没有具体说明(或者我读过头了)你在使用什么样的关系。如果你使用的是一对一的关系,比如“has_one”,那么创建将不起作用。在这种情况下,您必须使用以下内容:
在parent.rb中
has_one :child
before_create {|parent| parent.build_child(self)}
在你创建之后,它可能也能工作,但我还没有测试过
在child.rb中时
belongs_to :parent
在我当前的应用程序中设置用户模型时,我一直在努力解决这个问题
您可以看到has_one不支持parent.build或parent.create
希望这有帮助。我对Ruby还不熟悉,慢慢地开始穿越Ruby丛林。旅途愉快,但容易迷失方向。:) 我的示例中的子模型被称为“user\u info”,当我尝试执行user\u info.create(:main=>true)
时,它会出错,并实际为nil:NilClass说未定义的方法“create”
,该模型在技术上称为userInfo
userInfo.create在这种情况下不正确,因为它不会自动处理所属模型的外键。使用user_infos.create或create_user_info,如答案所示@Reti:模型应该是UserInfo,而不是UserInfo。如果模型名真的是userInfo,那么您有一个更深层次的问题需要修复(最佳)或解决。