Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 混合自指、多对多和多态关系_Ruby On Rails_Activerecord_Associations_Polymorphism_Self Reference - Fatal编程技术网

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