I have an interesting dilemma, and I'm not sure if this Rails can even handle something or not, so naked with me ...
I have two models: users and projects. The idea is that users can keep track of both projects and other users. Naturally, users and projects are part of a polymorphic “follow-up” type. Now, using a custom model, I would like to get three things:
user.followed_users
user.followed_projects
user.followers
The first two are working fine; This is the third one I'm having problems with. This is a kind of reverse lookup when the foreign key becomes the “followable_id” column in the following table, but no matter how I model it, I cannot get the query to work correctly.
User model
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"
Follow the model
class Follow < ActiveRecord::Base
belongs_to :followable, :polymorphic => true
belongs_to :user
end
:
followable_id
followable_type
, , :
SELECT `users`.* FROM `users` INNER JOIN `follows` ON `users`.`id` = `follows`.`user_id` WHERE `follows`.`user_id` = 7
"followable_id = 7 AND followable_type =" ", " user_id = 7 "
?