sent-hil
sent-hil

Reputation: 19305

Correct this Rails/ruby method for me, please?

I've a post model with act-as-taggable-on gem. Both tables have timestamps.

I started with

def tags
  @posts = current_user.posts.find_tagged_with(params[:tag], :order => "@posts.tags.updated_at DESC"])
end

And when that didn't work, I tried changing things and ended up with this mess.

def tags
  @posts = current_user.posts.find_tagged_with(params[:tag])
  @tags = @posts.tags.all
  @posts = @tags(params[:tag, :order => "@posts.tags.updated_at DESC"])
end

I basically want to sort by when the tags was last updated.

Bonus: Sort by tag.updated_at or post.updated_at, but in this particular app, I'll be updating tags the most, so just first one will be fine.

Any help is appreciated.

Upvotes: 0

Views: 83

Answers (1)

mikezter
mikezter

Reputation: 2463

You have to join the tags table in your find statement:

def tags
  @posts = Post.find_tagged_with(
    params[:tag], 
    :conditions => {:user_id => current_user.id}, 
    :joins => :tags, 
    :order => 'tags.updated_at DESC',
    :group => 'posts.id'
  )
end

Note: Find the right conditions to select only posts from the current user. This example could work, though.

Upvotes: 1

Related Questions