我有 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/