rails - 使用 :select(distinct) 和 :has_many :through 关联会产生无效的 SQL [英] rails - using :select(distinct) with :has_many :through association produces invalid SQL

查看:21
本文介绍了rails - 使用 :select(distinct) 和 :has_many :through 关联会产生无效的 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')

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

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

至少有其他人遇到过同样的问题:http://www.ruby-forum.com/topic/484938

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

功能还是错误?

谢谢

推荐答案

放在作用域上看起来不太合适.

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

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

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

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

这篇关于rails - 使用 :select(distinct) 和 :has_many :through 关联会产生无效的 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆