Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.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_Associations_Polymorphism - Fatal编程技术网

Ruby on rails 反向有许多多态性

Ruby on rails 反向有许多多态性,ruby-on-rails,associations,polymorphism,Ruby On Rails,Associations,Polymorphism,我有两个模型:用户和项目。这个想法是用户可以同时关注项目和其他用户。当然,用户和项目属于多态的“可跟随”类型。现在,使用用户模型,我想得到三件事: user.followed_users user.followed_projects user.followers 前两个工作很好;这是我遇到麻烦的第三个。这是一种反向查找,其中外键成为下表中的“followable_id”列,但无论我如何建模,都无法使查询正确运行 用户模型 has_many :follows, :dependent =>

我有两个模型:用户和项目。这个想法是用户可以同时关注项目和其他用户。当然,用户和项目属于多态的“可跟随”类型。现在,使用用户模型,我想得到三件事:

user.followed_users
user.followed_projects
user.followers
前两个工作很好;这是我遇到麻烦的第三个。这是一种反向查找,其中外键成为下表中的“followable_id”列,但无论我如何建模,都无法使查询正确运行

用户模型

has_many :follows, :dependent => :destroy
has_many :followed_projects, :through => :follows, :source => :followable, :source_type => "Project"
has_many :followed_users, :through => :follows, :source => :followable, :source_type => "User"
has_many :followers, :through => :follows, :as => :followable, :foreign_key => "followable", :source => :user, :class_name => "User"
仿效

class Follow < ActiveRecord::Base
  belongs_to :followable, :polymorphic => true
  belongs_to :user
end
其中,它应该是“followable_id=7,followable_type='User”,而不是“User_id=7”


有什么想法吗?

我想你需要明确地说出外键。你有:

:foreign_key => "followable"
你需要:

:foreign_key => "followable_id"
完整代码:

has_many :followers, :through => :follows, :as => :followable, :foreign_key => "followable_id", :source => :user, :class_name => "User"

我明白了。查看了一个,注意到正确的方法是不仅指定一个关系表(在本例中如下),而且指定一个反向关系表(我称之为反向如下)


希望这能帮助一些人走出困境

不,如果您不包括它,Rails会自动附加“\u id”。我只是试了一下,但还是没有运气
has_many :followers, :through => :follows, :as => :followable, :foreign_key => "followable_id", :source => :user, :class_name => "User"
    has_many    :follows,
                        :dependent => :destroy

    has_many    :followed_projects,
                        :through => :follows,
                        :source => :followable,
                        :source_type => "Project"

    has_many    :followed_users,
                        :through => :follows,
                        :source => :followable,
                        :source_type => "User"

    has_many    :reverse_follows,
                        :as => :followable,
                        :foreign_key => :followable_id,
                        :class_name => "Follow"

    has_many    :followers,
                        :through => :reverse_follows,
                        :source => :user