Ruby on rails 混合自指、多对多和多态关系
我正在开发一些应用程序,我有用户、帖子和报告模型,用户可以报告其他用户或帖子。所以我这样做了:Ruby on rails 混合自指、多对多和多态关系,ruby-on-rails,activerecord,associations,polymorphism,self-reference,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_m
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
...
我得到一个错误,说:
User reports another user
Failure/Error: @reporter.reported_users.size.should == 1
expected: 1
got: 0 (using ==)
无法找出问题所在,我可以在一个模型中同时使用
has\u many:reports
和has\u many:reports,:as=>:reportable
吗?还有,我如何为用户获取记者?假设我想要有@user.reporters
来获取报告某个特定用户的所有其他用户。将第二个的has-many:reports更改为has-many:reverse\u 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
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