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 :reportshas_many :reports, :as => :reportable?另外,我怎樣才能得到一個用戶的記者?假設我想讓@user.reporters獲得所有報告特定用戶的其他用戶。

回答

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