混合自我指涉,多对多和多态关系

时间:2012-06-04 04:50:23

标签: ruby-on-rails activerecord associations polymorphism self-reference

我正在处理某个应用,我有用户,发布和报告模型,因此用户可以报告其他用户或帖子。所以我这样做了:

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

我的用户规范如下:

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

我得到一个错误说:

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

无法弄清楚什么是错的,我可以在模型中一起使用has_many :reportshas_many :reports, :as => :reportable吗?另外,如何让用户获得记者?让我们说我希望@user.reporters让所有其他用户报告特定用户。

1 个答案:

答案 0 :(得分:0)

将第二个has_many :reports更改为has_many :inverse_reports解决了问题:

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

现在我想我也可以为每个用户找到记者:

  has_many :reporters, :through => :inverse_reports, :source => :user