Я работаю над некоторым приложением, у меня есть модели User, Post и Report, чтобы пользователи могли сообщать другим пользователям или сообщениям. Так что я сделал это:Смешивание Self Referencial, от многих до многих и полиморфных отношений
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
, чтобы получить всех других пользователей, которые сообщили о конкретном пользователе.