rails - using:select(distinct)with:has_many:通过关联产生无效的SQL

时间:2010-11-19 20:56:12

标签: ruby-on-rails activerecord scope

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')

使用Rails 3.0.4,我得到无效的SQL: SELECT post_tags。*,distinct tag_id ...

至少有一个人遇到了同样的问题:http://www.ruby-forum.com/topic/484938

功能还是错误?

感谢

1 个答案:

答案 0 :(得分:3)

放置范围看起来不合适。

也许你正在努力实现这个目标:

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

编辑:现在我知道你需要什么了:

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

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