0

我现在的迁移:

class CreateActivities < ActiveRecord::Migration
  def self.up
    create_table :activities do |t|
      t.integer :account_id, :null => false
      t.integer :target_id, :null => false
      t.string  :target_type, :null => false
      t.string  :event_type, :null => false
      t.integer :employee_id
      t.string  :name
      t.timestamps
    end

    add_index :activities, [:target_id, :target_type]

有了这个,我现在可以像这样调用目标:

Activity.first.target

它会根据 target_type 调出 target_id。

我将如何做相反的事情,以便我可以选择一个目标,如果它有任何相关的活动,它们会出现?

像这样:

Job.find(1234).activities
# Where Job.find(1234) is the target_id of many activities.
4

1 回答 1

1

如果我理解正确,应该这样做:

class Job < ActiveRecord::Base
  has_many :activities, :conditions => ['target_type = ?', 'Job'], :as => :target
end
于 2012-05-22T19:14:37.533 回答