0

我正在开发一些应用程序,我有用户、帖子和报告模型,因此用户可以报告其他用户或帖子。所以我这样做了:

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 :reports和吗?has_many :reports, :as => :reportable另外,如何为用户获取记者?假设我想@user.reporters获得所有报告特定用户的其他用户。

4

1 回答 1

0

更改第二个has_many :reportshas_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
于 2012-06-04T12:50:44.687 回答