加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Activerecord,其中带有连接的条件没有表名前缀

发布时间:2020-12-17 02:07:51 所属栏目:百科 来源:网络整理
导读:我有2张桌子.我使用表前缀x_. 用户(表x_users) 评论(表x_comments) 我想在内部联接后找出总数. 此查询工作正常. User.joins(:comments).where(x_comments: {something: 1}).count 如何从where条件中删除x_以使此调用通用? 楷模 class User ActiveRecord::Ba
我有2张桌子.我使用表前缀x_.

>用户(表x_users)
>评论(表x_comments)

我想在内部联接后找出总数.

此查询工作正常.

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

解决方法

正如@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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读