gpt4 book ai didi

ruby-on-rails - ruby rails : Save objects and attributes of model to another table

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:03 25 4
gpt4 key购买 nike

我有 2 个表。例如“Fruits”和“Food” 当我用相应的模型为 Fruits 表创建一个新条目时,如何将这个表的对象和属性保存到另一个名为 All 的表中?

或者更简单:如何在保存新条目时更新另一个表?

我需要像“更新 id=x 的值”这样的东西

最佳答案

你必须做这样的事情:

class Fruits < ActiveRecord::Base

after_save :update_the_all_table

private

def update_the_all_table
allobject = All.find(self.id)
allobject.someattribute = self.someattribute # self is the fruit
allobject.save
end

end

如你所知,如果你不想写“私有(private)”,你也可以执行以下操作!

class Fruits < ActiveRecord::Base

after_save { |fruit|
allobject = All.find(fruit.id)
allobject.someattribute = fruit.someattribute
allobject.save
}

end

关于ruby-on-rails - ruby rails : Save objects and attributes of model to another table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6612108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com