ruby-on-rails - rails - 使用 :select(distinct) with :has_many :through association produces invalid SQL

标签 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.*, 不同的 tag_id...

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

功能还是错误?

谢谢

最佳答案

放在示波器上看起来不太合适。

也许您正在尝试实现这一点:

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

关于ruby-on-rails - rails - 使用 :select(distinct) with :has_many :through association produces invalid SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4229284/

相关文章:

ruby-on-rails-3 - Rails 3 更新连接表的属性(有很多,通过关联)

ruby-on-rails - rails : rollback from after_create without throwing Exception

javascript - 具有多个实例的原型(prototype)上的私有(private)成员

c++ - 如何根据类访问特定的 protected 继承成员?

ruby-on-rails - Rails 表单帮助 has_one belongs_to 关联

ruby-on-rails - Rails 如何随机选择表格中的一行?

ruby-on-rails - 是否可以添加 "somewhere"一个 `before(:each)` Hook ,以便所有规范文件都可以运行它?

javascript - 部署 Ruby On Rails 项目时出现意外的 INDENT

ruby-on-rails - 仅将日期时间的日期与当前日期进行比较

java - Spring 4 不支持 scope 属性吗?