user753676
user753676

Reputation:

Ruby on Rails: Save objects and attributes of model to another table

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

Answers (3)

Stepan Zakharov
Stepan Zakharov

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

Dominic Goulet
Dominic Goulet

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

cam
cam

Reputation: 14222

You can use Callbacks to perform actions on events like save.

Be wary about duplicating data, if you are just trying to create a table containing all the same information as other tables you may just need to query your data differently.

Upvotes: 1

Related Questions