我怎样才能给出别名includes()?以下是:
这里有一些例子:
第一个案例(更多STI协会)
Project.all.includes(:students, :teachers).order('teachers_projects.name ASC') # order on teachers
Project.all.includes(:students, :teachers).order('users.name ASC') # order on students
Run Code Online (Sandbox Code Playgroud)
Rails的自动使用别名teachers_projects为:teachers在SQL.我怎样才能覆盖这个,以便我可以使用别名teachers而不是teachers_projectsSQL?:students获取别名users.
这个例子失败了:
Project.all.includes(:students, :teachers).order('teachers.name ASC')
Project.all.includes(:students, :teachers).order('students.name ASC')
Project.all.includes(:students, :teachers).order('students_projects.name ASC')
Run Code Online (Sandbox Code Playgroud)
第二个案例(一个STI协会)
如果我只使用:students(不:teachers)方法includes(),Rails使用STI基类名称的名称别名users(没有_projects附加):students:
Project.all.includes(:students).order('users.name ASC') # order on students
Run Code Online (Sandbox Code Playgroud)
这个例子失败了:
Project.all.includes(:students).order('students.name ASC')
Project.all.includes(:students).order('students_projects.name ASC')
Run Code Online (Sandbox Code Playgroud)
题
可能存在类似于:
Project.all.includes(:students).alias(students: :my_alias)
Run Code Online (Sandbox Code Playgroud)
RAILS ALIAS TRACKER
测试应用程序 …
activerecord ruby-on-rails arel ruby-on-rails-3 ruby-on-rails-4
使用包含范围的模型关注点,知道嵌套和/或自引用查询的最佳方法是什么?
在我的一个问题中,我的范围类似于这些:
scope :current, ->(as_at = Time.now) { current_and_expired(as_at).current_and_future(as_at) }
scope :current_and_future, ->(as_at = Time.now) { where("#{upper_bound_column} IS NULL OR #{upper_bound_column} >= ?", as_at) }
scope :current_and_expired, ->(as_at = Time.now) { where("#{lower_bound_column} IS NULL OR #{lower_bound_column} <= ?", as_at) }
def self.lower_bound_column
lower_bound_field
end
def self.upper_bound_column
upper_bound_field
end
Run Code Online (Sandbox Code Playgroud)
并通过has_many来引用,例如: has_many :company_users, -> { current }
如果进行ActiveRecord查询,该查询引用包含关注点的少数模型,则会导致"模糊列名称"异常,这是有意义的.
为了帮助解决这个问题,我将列名称辅助方法更改为现在
def self.lower_bound_column
"#{self.table_name}.#{lower_bound_field}"
end
def self.upper_bound_column
"#{self.table_name}.#{upper_bound_field}"
end
Run Code Online (Sandbox Code Playgroud)
哪种方法很有效,直到您需要自引用查询.Arel通过在生成的SQL中对表名进行别名来帮助缓解这些问题,例如:
LEFT OUTER JOIN "company_users" "company_users_companies" ON "company_users_companies"."company_id" = "companies"."id"
和
INNER JOIN "company_users" ON …