Ruby on Rails:将模型的对象和属性保存到另一个表中

时间:2011-07-07 14:20:47

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord callback

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

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

我需要类似“更新值,其中id = x”

3 个答案:

答案 0 :(得分:4)

你必须做这样的事情:

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 :(得分:1)

您可以使用Callbacks对保存等事件执行操作。

警惕重复数据,如果您只是想创建一个包含与其他表相同信息的表,您可能只需要以不同方式查询数据。

答案 2 :(得分:0)

本案例中的最佳做法是使用observers

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)运行服务器/控制台并检查出来!