假设我有 2 个模型model1 and model2. model1有很多model2. model2 belongs to model1. Save model1 and model2同时。
class Model1 < ActiveRecord::Base
has_many :model2s
end
class Model2 < ActiveRecord::Base
belongs_to :model1
end
def create
@mod1 = Model1.new(model1_params)
id = Model1.last.id + 1
@mod2 = Model2.new(model1_id: id)
if @mod1.save && @mod2.save
redirect root_path
else
render 'edit'
end
end
在我删除 model1 的最后一条记录之前,该解决方案是可以的。如何获取 model1 创建之前的最后一条记录。
最符合规范的方法是这样的:
def create
@mod1 = Model1.new(model1_params)
@mod1.model2.build({args if you have them}) # this will only work if you have the relationship set up
if @mod1.save
# @mod1 is now saved along with model 2 who now has its ID
# @mod1.id returns id, Model2.last returns model2 ID, Model2.last.model1_id returns Model1 ID
#you can now delete model 1 if you wanted to, just make sure you don't have dependent destroy on in the model1.
redirect root_path
else
render 'edit'
end
end
希望能帮助到你!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)