Reputation:
I have 2 tables. For example "Fruits" and "Food" When I create a new entry for the Fruits table with the corresponding model, how do I save objects and attributes of this one to the other table called All?
Or easier: How to update another table when saving a new entry?
i need something like "update value where id=x"
Upvotes: 1
Views: 3352
Reputation: 420
The best practice in this case is using observers.
1) Add to your Gemfile
:
gem 'rails-observers'
2) Run:
bundle install
3) Create new file 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) Add to your application.rb
:
config.active_record.observers = :fruit_observer
5) Run server/console and check this out!
Upvotes: 0
Reputation: 8113
You have to do something like this :
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
Just so you know, you can also do the following if you don't want to write the "private" !
class Fruits < ActiveRecord::Base
after_save { |fruit|
allobject = All.find(fruit.id)
allobject.someattribute = fruit.someattribute
allobject.save
}
end
Upvotes: 3