0

I'm working on some app, I have User, Post and Report models so users can report other users, or posts. So I did this:

class Report < ActiveRecord::Base
  belongs_to :user
  belongs_to :reportable, :polymorphic => true
  ...

class User < ActiveRecord::Base
  has_many :reports, :dependent => :destroy
  has_many :reported_users, :through => :reports, :source => :reportable, :source_type => 'User'
  has_many :reported_posts, :through => :reports, :source => :reportable, :source_type => 'Post'
  has_many :reports, :as => :reportable, :dependent => :destroy
  ...

class Post < ActiveRecord::Base
  has_many :reports, :as => :reportable, :dependent => :destroy
  ...

And my user spec looks like:

it 'reports another user' do
  @reporter = FactoryGirl.create(:user)
  @reported = FactoryGirl.create(:user)
  Report.create!(:user => @reporter, :reportable => @reported)
  Report.count.should == 1
  @reporter.reported_users.size.should == 1
end

And I get an error saying:

User reports another user
Failure/Error: @reporter.reported_users.size.should == 1
  expected: 1
       got: 0 (using ==)

Can't figure out whats wrong, can I use has_many :reports and has_many :reports, :as => :reportable together in a model? Also, how can I get the reporters for a user? Let's say I want to have @user.reporters to get all other users who have reported a particular user.

Soheil Jadidian
  • 878
  • 7
  • 12

1 Answers1

0

Changing the second has_many :reports to has_many :inverse_reports solved the problem:

class User < ActiveRecord::Base
  has_many :reports, :dependent => :destroy
  has_many :reported_users, :through => :reports, :source => :reportable, :source_type => 'User'
  has_many :reported_posts, :through => :reports, :source => :reportable, :source_type => 'Post'
  has_many :inverse_reports, :class_name => 'Report', :as => :reportable, :dependent => :destroy

Now I guess I can also get the reporters for each user like:

  has_many :reporters, :through => :inverse_reports, :source => :user
Soheil Jadidian
  • 878
  • 7
  • 12