【问题标题】:Activerecord where condition with join without table name prefixActiverecord where 条件与不带表名前缀的连接
【发布时间】:2015-04-11 08:17:06
【问题描述】:

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

  1. 用户(表 x_users)
  2. 评论(表 x_cmets)

我想知道内部连接后的总数。

这个查询工作正常。

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

【问题讨论】:

  • User.joins(:follows).where(follows: {something: 1}).count 不起作用吗?您的用户关联是与follows,所以它应该可以工作。
  • 也发布你的模型
  • 您可以改用Comment.table_name =&gt;
  • @RAJ :更新了模型并添加了类定义。
  • @BroiSatse:这行得通。这是一种适当的轨道方式还是解决方法?谢谢。

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


【解决方案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"

【讨论】:

    【解决方案2】:

    考虑将您的条件编写为范围,并让 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      相关资源
      最近更新 更多