Activerecord where condition with join without table name prefix

I have 2 tables. I use the table prefix x _.

  • User (table x_users)
  • Comment (table x_comments)

I want to know the total after inner join.

This request is working fine.

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

How to remove x_ from a condition to make this call shared?

Models

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

class Comment < ActiveRecord::Base
    attr_accessible :something
    belongs_to :user
end
+4
source share
2 answers

As @BroiSatse already mentioned, you can use ActiveRecord::Base.table_nameto explicitly specify the table name in the model and get the table name in the query for universality.

The request will look like this:

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

Directly setting the table name:

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

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 .

,

User.for_comments_something(1).count
0

All Articles