开发者

Help with active record relations

开发者 https://www.devze.com 2023-02-01 23:34 出处:网络
class CreateActivities < ActiveRecord::Migration def self.up cre开发者_开发百科ate_table :activities do |t|
class CreateActivities < ActiveRecord::Migration
  def self.up
    cre开发者_开发百科ate_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

I tried changing my activity model too, without any success:

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

One thing to note. Activity is an STI. Fan inherits from Activity.

In console, I do:

# 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, .....

But...

Activity.last.artist
 => nil 

Why is Activity.last.artist returning nil?


What I notice is artist_id is always nil when I try to create the fan object using .create!, as such:

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">

Why is this?


Ok. It seems I had

attr_accessor :artist

in my Fan model. Removed it and now works accordingly

0

精彩评论

暂无评论...
验证码 换一张
取 消