[英]Ruby on Rails: Save objects and attributes of model to another table
我有 2 张桌子。 例如“Fruits”和“Food” 当我为 Fruits 表创建一个具有相应 model 的新条目时,如何将这个表的对象和属性保存到另一个名为 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
如您所知,如果您不想写“私人”,也可以执行以下操作!
class Fruits < ActiveRecord::Base
after_save { |fruit|
allobject = All.find(fruit.id)
allobject.someattribute = fruit.someattribute
allobject.save
}
end
您可以使用回调对保存等事件执行操作。
小心重复数据,如果您只是想创建一个包含与其他表相同的所有信息的表,您可能只需要以不同的方式查询您的数据。
在这种情况下,最佳实践是使用观察者。
1)添加到您的Gemfile
:
gem 'rails-observers'
2)运行:
bundle install
3) 创建新文件app/models/fruit_observer.rb
:
class FruitObserver < ActiveRecord::Observer
def after_save(fruit)
# Any actions with other models and tables must stay here.
# Example:
All.create(
name: fruit.name,
entitable_type: fruit.class.to_s,
entitable_id: fruit.id
)
end
end
4)添加到您的application.rb
:
config.active_record.observers = :fruit_observer
5)运行服务器/控制台并检查一下!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.