Ruby on rails 如何以rails方式获取新创建记录的id?
我有两个模型,假设model1和model2model1有许多model2model2属于model1。同时保存model1和model2Ruby on rails 如何以rails方式获取新创建记录的id?,ruby-on-rails,Ruby On Rails,我有两个模型,假设model1和model2model1有许多model2model2属于model1。同时保存model1和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 =
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
classmodel1
在我删除model1的最后一条记录之前,该解决方案是正常的。如何获取model1创建前的最后一条记录。无法获取尚未创建的记录的id。 解决方案的最佳答案是首先保存@mod1。并获取其id的id
如果您的Model1和Model2子类
ActiveRecord::Base
,则无需手动设置id,事实上它是一种反模式
Rails使用ActiveRecord::Base
对一个架构支持的类进行建模。假设您有一个名为model1s
的数据库表。当您创建这样的Model1类时
class Model1 < ActiveRecord::Base
end
还有一些建议。Model2的model1\u id
属性看起来像是外键。您应该研究如何利用has_many/has_one/belies_to associations,以更惯用的方式实现您想要的目标
class Model1 < ActiveRecord::Base
has_one :model2
end
class Model2 < ActiveRecord::Base
belongs_to :model1
end
# Then you can do (one of the many options)
@mod1 = Model1.create(params)
@mod1.model2.create
classmodel1
检查导轨上的导轨很有用
我假设您使用的是ActiveRecord,因为您使用的是
.last
和.save
方法。我希望我的直觉是正确的。最有效的方法是:
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
希望有帮助 这是工作代码,但不是很有讽刺意味。rails的方法是使用AR关系(
在本例中属于
),与原始代码不同,此关系不设置@mod2
,这可能会在编辑
视图中使用。此外,您可能应该将所有内容包装在事务中。还请注意创建
(与保存
不同)始终返回真实值。id=Model1.last.id+1
--哇,哇,哇。。。不要那样做。在多个层面上,这是一个非常糟糕的想法。如果两个用户同时执行create
操作,会发生什么情况?(您将获得由竞赛条件引起的错误关联。)如果记录已被删除,会发生什么情况?(您将获得错误的ID,因为自动递增索引将跳过一个值。)如果这是要创建的Model1
的第一个实例,会发生什么情况?(您将得到一个未定义的方法错误,因为Model1。last
是nil
)Model1
和Model2
之间的关系如何?是1-1还是1-n?它们是否总是成对出现,或者Model1
不存在Model2
(反之亦然)?如果删除了相关记录,会发生什么情况?
class Model1 < ActiveRecord::Base
has_one :model2
end
class Model2 < ActiveRecord::Base
belongs_to :model1
end
# Then you can do (one of the many options)
@mod1 = Model1.create(params)
@mod1.model2.create
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