rails - using :select(distinct) with :has_many :th

2020-03-24 09:02发布

问题:

User
has_many :posts
has_many :post_tags, :through => :posts

PostTag
belong_to :post
belongs_to :tag
scope :distincttag, :select => ('distinct post_tags.tag_id')

with Rails 3.0.4, i get invalid SQL: SELECT post_tags.*, distinct tag_id...

at least one other person experienced the same problem: http://www.ruby-forum.com/topic/484938

feature or a bug?

thanks

回答1:

Does not look like the right thing to put on a scope.

Maybe you are trying to accomplish this:

class PostTag < ...
  belong_to :post
  belongs_to :tag
  def distincttag
    find(:all, :select => 'distinct tag_id')
  end
end

Edit: now that I know what you need:

User
has_many :posts
has_many :post_tags, :through => :posts, :select => 'distinct tags.*'
# or, if you are not worried about database overhead:
has_many :post_tags, :through => :posts, :uniq => true

Reference: http://blog.hasmanythrough.com/2006/5/6/through-gets-uniq