mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #33611 from willianveiga/feature/reselect-method
Add reselect method
This commit is contained in:
commit
0c4bf982e8
4 changed files with 58 additions and 0 deletions
|
@ -382,6 +382,12 @@
|
|||
|
||||
*Federico Martinez*
|
||||
|
||||
* Add `reselect` method. This is a short-hand for `unscope(:select).select(fields)`.
|
||||
|
||||
Fixes #27340.
|
||||
|
||||
*Willian Gustavo Veiga*
|
||||
|
||||
* Add basic API for connection switching to support multiple databases.
|
||||
|
||||
1) Adds a `connects_to` method for models to connect to multiple databases. Example:
|
||||
|
|
|
@ -240,6 +240,27 @@ module ActiveRecord
|
|||
self
|
||||
end
|
||||
|
||||
# Allows you to change a previously set select statement.
|
||||
#
|
||||
# Post.select(:title, :body)
|
||||
# # SELECT `posts.title`, `posts.body` FROM `posts`
|
||||
#
|
||||
# Post.select(:title, :body).reselect(:created_at)
|
||||
# # SELECT `posts.created_at` FROM `posts`
|
||||
#
|
||||
# This is short-hand for <tt>unscope(:select).select(fields)</tt>.
|
||||
# Note that we're unscoping the entire select statement.
|
||||
def reselect(*args)
|
||||
check_if_method_has_arguments!(:reselect, args)
|
||||
spawn.reselect!(*args)
|
||||
end
|
||||
|
||||
# Same as #reselect but operates on relation in-place instead of copying.
|
||||
def reselect!(*args) # :nodoc:
|
||||
self.select_values = args
|
||||
self
|
||||
end
|
||||
|
||||
# Allows to specify a group attribute:
|
||||
#
|
||||
# User.group(:name)
|
||||
|
|
|
@ -11,5 +11,10 @@ module ActiveRecord
|
|||
expected = Post.select(:title).to_sql
|
||||
assert_equal expected, Post.select(nil).select(:title).to_sql
|
||||
end
|
||||
|
||||
def test_reselect
|
||||
expected = Post.select(:title).to_sql
|
||||
assert_equal expected, Post.select(:title, :body).reselect(:title).to_sql
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -807,6 +807,32 @@ SELECT * FROM articles WHERE id > 10 ORDER BY id DESC LIMIT 20
|
|||
|
||||
```
|
||||
|
||||
### `reselect`
|
||||
|
||||
The `reselect` method overrides an existing select statement. For example:
|
||||
|
||||
```ruby
|
||||
Post.select(:title, :body).reselect(:created_at)
|
||||
```
|
||||
|
||||
The SQL that would be executed:
|
||||
|
||||
```sql
|
||||
SELECT `posts.created_at` FROM `posts`
|
||||
```
|
||||
|
||||
In case the `reselect` clause is not used,
|
||||
|
||||
```ruby
|
||||
Post.select(:title, :body)
|
||||
```
|
||||
|
||||
the SQL executed would be:
|
||||
|
||||
```sql
|
||||
SELECT `posts.title`, `posts.body` FROM `posts`
|
||||
```
|
||||
|
||||
### `reorder`
|
||||
|
||||
The `reorder` method overrides the default scope order. For example:
|
||||
|
|
Loading…
Reference in a new issue