Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activerecord where condition with join without table name prefix

I have 2 tables. I use table prefix x_.

  1. User (table x_users)
  2. Comment (table x_comments)

I want to find out total count after inner join.

This query works fine.

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

How can I remove x_ from where condition to make this call generic?

Models

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

class Comment < ActiveRecord::Base
    attr_accessible :something
    belongs_to :user
end
like image 219
geek_guy Avatar asked Nov 09 '22 16:11

geek_guy


1 Answers

As @BroiSatse already mentioned, You can use ActiveRecord::Base.table_name to set the table name explicitly in a model and to get the table name in a query for genericity.

You query would be:

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

Setting a table name explicitly:

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

You can override the table_name method like this:

class Comment < ActiveRecord::Base
  def self.table_name
    "x_" + super
  end
end
Comment.table_name # => "x_comments"
like image 122
Sharvy Ahmed Avatar answered Nov 15 '22 06:11

Sharvy Ahmed