Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow order to be given expressions as hash keys #28191

Merged
merged 1 commit into from Mar 17, 2017

Conversation

eugeneius
Copy link
Member

@eugeneius eugeneius commented Feb 26, 2017

Related to #28117.

When order is given a hash, the keys are currently assumed to be attribute names and are quoted as such in the query, which makes it impossible to pass an expression instead:

Post.order("LENGTH(title)" => :asc).last
# SELECT  `posts`.* FROM `posts` ORDER BY `posts`.`LENGTH(title)` DESC LIMIT 1

If the key is an Arel::Nodes::SqlLiteral, we now use it directly in the query. This provides a way to build a relation with a complex order clause that can still be reversed with reverse_order or last.

@matthewd
Copy link
Member

This seems like a good idea, but we should probably coordinate it with #27947: allow an Arel.sql expression, but not start treating a plain string as such.

When `order` is given a hash, the keys are currently assumed to be
attribute names and are quoted as such in the query, which makes it
impossible to pass an expression instead:

    Post.order("LENGTH(title)" => :asc).last
    # SELECT  `posts`.* FROM `posts` ORDER BY `posts`.`LENGTH(title)` DESC LIMIT 1

If the key is an `Arel::Nodes::SqlLiteral`, we now use it directly in
the query. This provides a way to build a relation with a complex order
clause that can still be reversed with `reverse_order` or `last`.
@eugeneius
Copy link
Member Author

I've restricted the behaviour to only apply to Arel SQL literals - thanks @matthewd!

Copy link
Member

@rafaelfranca rafaelfranca left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@rafaelfranca rafaelfranca added this to the 5.1.0 milestone Feb 28, 2017
@rafaelfranca rafaelfranca merged commit bac40b9 into rails:master Mar 17, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants