Reputation:
class Post
has_many :tags
class Tag
belongs_to :post
I need a query that returns all posts limited to n per tag.
Given the following set of posts (tagged with hashtags like on Twitter):
#1: Post A #letter
#2: Post B #letter
#3: Post 1 #number
#4: Post C #letter
#5: Post 2 #number
I would want to get all of the latest 2 posts per tag, giving me the following result:
#5: Post 2 #number
#4: Post C #letter
#3: Post 1 #number
#2: Post B #letter
I've been looking up how to do this for a few hours now, but only found results (like this) that use MySQL variables and don't know how to translate it to Rails.
I still don't know where to begin tackling this so any help is appreciated; thanks!
Upvotes: 0
Views: 187
Reputation: 76784
Maybe you could try:
@post = Post.joins(:tags).where(tags: {name: "letter"}).order(created_at: :desc).limit(2)
This uses the joins
ActiveRecord method, with the hash conditions on the where
clause, ordering by created_at (to give latest), and limiting the response to 2 records
This should work for a single tag; if you wanted to extend to multiple tags, I'd use the SQL method GROUP_BY
, (ActiveRecord .group
), like this:
@post = Post.joins(:tags).where(tags: {name: "letter", name: "number"}).order(created_at: :desc).group("tags.name").limit(2)
Upvotes: 0
Reputation: 3046
Try this code
def get_tags(n)
Tags.order('id desc').select("DISTINCT(NAME)").each do |tag|
Post.where(tag: tag).limit(n)
end
end
This link may help you, if not work Unique select from database
Upvotes: 1