Rails 4 - how to give alias names to includes() and joins() in active record querying

前端 未结 2 1765
日久生厌
日久生厌 2021-02-02 15:08

How can I give an alias name for e.g. includes()? Following is given:

  • User: active record model
  • Student: active record model, inherits from
2条回答
  •  春和景丽
    2021-02-02 15:48

    Arel does actually have an alias method.

    student_alias = Student.arel_table.alias(:my_student_table_alias)
    

    caveat: this will require you to use even more handcrafted Arel and do the join manually. And the joins in Arel can get a bit complicated if you're not used to them.

    student_alias_join = student_alias.create_on(
      Project.arel_table[:primary_key].eq(student_alias[:project_id])
    )
    
    Project.joins(
      Project.arel_table.create_join(
        student_alias, student_alias_join, Arel::Nodes::OuterJoin
      )
    ).order(...)
    

    Something like this should do it. Of course putting this into some Class method with :my_student_table_alias as parameter would make it more tidy and reusable as this would look a bit messy in a controller.

提交回复
热议问题