我正在开发一些应用程序,我有用户、帖子和报告模型,因此用户可以报告其他用户或帖子。所以我这样做了:
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
获得所有报告特定用户的其他用户。