Ordering by number of associations in common even if none (rails)

天大地大妈咪最大 提交于 2019-12-12 05:05:20

问题


I am working on a project which has a very similar quandary to this ask: Ordering by number of associations in common (Rails)

The asker of said ask (Neon) writes,

BACKGROUND: I have Posts and Users, and both have many Communities.

OBJECTIVE: For any given User I'd like to return a collection of Posts, ordered by how many communities the post has in common with the user (posts with more communities in-common being higher up)

Unfortunately, the solution only includes posts that have at least one common community. My quandry needs to include all posts ordered by the number of common communities.

EXTENDED OBJECTIVE: The result must be an AREL object with all posts ordered by the number of common communities, including posts with zero communities in common with the user (posts with more communities in-common being higher up).


回答1:


If you need to include posts with zero communities in common with the user you can use a LEFT JOIN. To sanitize the parameters that are sent in a join condition, we can define this in a class method so that the sanitize_sql_array method is available:

# Post class
def self.community_counts(current_user)
  current_user.posts.joins(sanitize_sql_array(["LEFT JOIN community_posts ON community_posts.post_id = posts.id AND community_posts.community_id IN (?)", current_user.community_ids])).select("posts.*, COUNT(DISTINCT community_posts.community_id) AS community_count").group("posts.id").order("community_count DESC")
end

Additional Info

An INNER JOIN returns the intersection between two tables. A LEFT JOIN returns all rows from the left table (in this case posts) and returns the matching rows from the right table (community_posts) but it also returns NULL on the right side when there is no match (posts with no communities that match the user's communities). See this answer for an illustration.

As far as I know Rails doesn't provide any helper methods to produce a LEFT JOIN. We have to write out the SQL for these.

LEFT JOIN is the same as LEFT OUTER JOIN (more info).



来源:https://stackoverflow.com/questions/30446662/ordering-by-number-of-associations-in-common-even-if-none-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!