ActiveRecord has_many through polymorphic has_many

It seems that the rails still do not support this type of relationship and throw an ActiveRecord :: HasManyThroughAssociationPolymorphicThroughError error.

What can I do to implement such an attitude?

I have the following associations:

Users 1..n Articles
Categories n..n Articles
Projects 1..n Articles

And here is the subscription model

Subscription 1..1 User
Subscription 1..1 Target (polymorphic (Article, Category or User))

And I need to select articles through the article #appointment #subscription according to subscription #user.

I have no idea to implement this.

Ideally, I want to get an instance of the Association class

UPDATE 1

Here is a small example

Let's say user_1 has 4 subscription entries:

s1 = (user_id: 1, target_id: 3, target_type: 'User')
s2 = (user_id: 1, target_id: 2, target_type: 'Category')
s3 = (user_id: 1, target_id: 3, target_type: 'Project')
s4 = (user_id: 1, target_id: 8, target_type: 'Project')

I need a User # feed_articles method that retrieves all articles belonging to any of the objects I signed up for.

user_1.feed_articles.order(created_at: :desc).limit(10) 

UPDATE 2

Separate source articles by type in user model:

  has_many :out_subscriptions, class_name: 'Subscription'

  has_many :followes_users, through: :out_subscriptions, source: :target, source_type: 'User'
  has_many :followes_categories, through: :out_subscriptions, source: :target, source_type: 'Category'
  has_many :followes_projects, through: :out_subscriptions, source: :target, source_type: 'Project'

  has_many :feed_user_articles, class_name: 'Article', through: :followes_users, source: :articles
  has_many :feed_category_articles, class_name: 'Article', through: :followes_categories, source: :articles
  has_many :feed_project_articles, class_name: 'Article', through: :followes_projects, source: :articles

feed_user_articles feed_category_category_articles feed_project_articles

3.1

, , SQL SQL. , , .

  def feed_articles
    join_clause = <<JOIN
inner join users on articles.user_id = users.id
inner join articles_categories on articles_categories.article_id = articles.id
inner join categories on categories.id = articles_categories.category_id
inner join subscriptions on
    (subscriptions.target_id = users.id and subscriptions.target_type = 'User') or
    (subscriptions.target_id = categories.id and subscriptions.target_type = 'Category')
JOIN

    Article.joins(join_clause).where('subscriptions.user_id' => id).distinct
  end

( )

. : - ?

+4
2

, , - UNION ALL, , . . Arel , ( ), , raw SQL. SQL ORDER BY .

0

, Rails has_many: w/ . , User. :

def articles
  Article.
    joins("join subscriptions on subscriptions.target_id = articles.id and subscriptions.target_type = 'Article'").
    joins("join users on users.id = subscriptions.user_id")
end
0

Source: https://habr.com/ru/post/1547454/


All Articles