帮助积极的记录关系

时间:2010-12-30 09:17:53

标签: ruby-on-rails activerecord

class CreateActivities < ActiveRecord::Migration
  def self.up
    create_table :activities do |t|
      t.references :user
      t.references :media
      t.integer :artist_id

      t.string :type
      t.timestamps
    end
  end

  def self.down
    drop_table :activities
  end
end

class Fan < Activity
  belongs_to :user, :counter_cache => true
end

class Activity < ActiveRecord::Base
  belongs_to :user
  belongs_to :media
  belongs_to :artist, :class_name => 'User', :foreign_key => 'artist_id'
end

class User < ActiveRecord::Base
  has_many :activities
  has_many :fans
end

我也尝试改变我的活动模型,但没有取得任何成功:

class Activity < ActiveRecord::Base
  has_many :activities, :class_name => 'User', :foreign_key => 'user_id'
  has_many :activities, :class_name => 'User', :foreign_key => 'artist_id'
end

有一点需要注意。活动是STI。粉丝继承自活动。

在控制台中,我这样做:

# Create a fan object. User is a fan of himself
fan = Fan.new
 => #<Fan id: nil, user_id: nil, media_id: nil, artist_id: nil, type: "Fan", comment: nil, created_at: nil, updated_at: nil> 

# Assign a user object
fan.user = User.first
 => #<User id: 1, genre_id: 1, country_id: 1, ....

# Assign an artist object
fan.artist_id = User.first.id
 => 1 

# Save the fan object
fan.save!
 => true 

Activity.last
 => #<Fan id: 13, user_id: 1, media_id: nil, artist_id: 1, type: "Fan", comment: nil, created_at: "2010-12-30 08:41:25", updated_at: "2010-12-30 08:41:25">

Activity.last.user
 => #<User id: 1, genre_id: 1, country_id: 1, .....

但是...

Activity.last.artist
 => nil 

为什么Activity.last.artist返回nil?

2 个答案:

答案 0 :(得分:0)

当我尝试使用.create!创建粉丝对象时,我注意到artist_id总是为nil:

Fan.create!(:user => User.first, :artist => User.first.id)
 => #<Fan id: 43, user_id: 4, media_id: nil, artist_id: nil, type: "Fan", comment: nil, created_at: "2010-12-30 10:05:19", updated_at: "2010-12-30 10:05:19"> 

Fan.create!(:user => User.first, :artist_id => User.first.id)
 => #<Fan id: 44, user_id: 4, media_id: nil, artist_id: nil, type: "Fan", comment: nil, created_at: "2010-12-30 10:06:33", updated_at: "2010-12-30 10:06:33"> 

Fan.create!(:user => User.first, :artist => User.first)
 => #<Fan id: 45, user_id: 4, media_id: nil, artist_id: nil, type: "Fan", comment: nil, created_at: "2010-12-30 10:06:59", updated_at: "2010-12-30 10:06:59">

为什么会这样?

答案 1 :(得分:0)

确定。好像我有

attr_accessor :artist

在我的粉丝模型中。删除它,现在相应地工作