Activerecord其中带有连接的条件没有表名前缀

时间:2015-04-11 08:17:06

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有2张桌子。我使用表前缀x _。

  1. 用户(表x_users)
  2. 评论(表x_comments)
  3. 我想在内部联接后找出总数。

    此查询正常。

    User.joins(:comments).where(x_comments: {something: 1}).count
    

    如何从where条件中删除x_以使此调用成为通用的?

    模型

    class User < ActiveRecord::Base
        has_many :comments, dependent: :destroy
    end
    
    class Comment < ActiveRecord::Base
        attr_accessible :something
        belongs_to :user
    end
    

2 个答案:

答案 0 :(得分:1)

正如@BroiSatse已经提到的,您可以使用ActiveRecord::Base.table_name在模型中显式设置表名,并在查询中获取表名以获得通用性。

您的查询将是:

User.joins(:comments).where(Comment.table_name: {something: 1}).count

明确设置表名:

class Comment < ActiveRecord::Base
  self.table_name = "x_comments"
end

您可以像这样覆盖table_name方法:

class Comment < ActiveRecord::Base
  def self.table_name
    "x_" + super
  end
end
Comment.table_name # => "x_comments"

答案 1 :(得分:0)

考虑将条件写为范围,让ActiveRecord为您处理表别名。

class User < ActiveRecord::Base
  has_many :comments, dependent: :destroy

  def self.for_comment_something(foo)
    joins(:comments).
    merge(Comment.for_something(foo))
  end
end

class Comment < ActiveRecord::Base
  attr_accessible :something
  belongs_to :user

  def self.for_something(foo)
    where(something: foo)
  end 
end

ActiveRecord :: Relation#merge的文档是here

一样把它们放在一起
User.for_comments_something(1).count