Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

activerecord - rails - using :select(distinct) with :has_many :through association produces invalid SQL

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...