diff options
Diffstat (limited to 'guides/source')
-rw-r--r-- | guides/source/active_record_querying.md | 56 |
1 files changed, 35 insertions, 21 deletions
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 66e6390f67..76548a3397 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -1225,17 +1225,17 @@ WARNING: Up to and including Rails 3.1, when the number of arguments passed to a Find or build a new object -------------------------- -It's common that you need to find a record or create it if it doesn't exist. You can do that with the `first_or_create` and `first_or_create!` methods. +It's common that you need to find a record or create it if it doesn't exist. You can do that with the `find_or_create_by` and `find_or_create_by!` methods. -### `first_or_create` +### `find_or_create_by` -The `first_or_create` method checks whether `first` returns `nil` or not. If it does return `nil`, then `create` is called. This is very powerful when coupled with the `where` method. Let's see an example. +The `find_or_create_by` method checks whether a record with the attributes exists. If it doesn't, then `create` is called. Let's see an example. -Suppose you want to find a client named 'Andy', and if there's none, create one and additionally set his `locked` attribute to false. You can do so by running: +Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running: ```ruby -Client.where(:first_name => 'Andy').first_or_create(:locked => false) -# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27"> +Client.find_or_create_by(first_name: 'Andy') +# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27"> ``` The SQL generated by this method looks like this: @@ -1243,27 +1243,39 @@ The SQL generated by this method looks like this: ```sql SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1 BEGIN -INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57') +INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 1, NULL, '2011-08-30 05:22:57') COMMIT ``` -`first_or_create` returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned. +`find_or_create_by` returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned. The new record might not be saved to the database; that depends on whether validations passed or not (just like `create`). -It's also worth noting that `first_or_create` takes into account the arguments of the `where` method. In the example above we didn't explicitly pass a `:first_name => 'Andy'` argument to `first_or_create`. However, that was used when creating the new record because it was already passed before to the `where` method. +Suppose we want to set the 'locked' attribute to true if we're +creating a new record, but we don't want to include it in the query. So +we want to find the client named "Andy", or if that client doesn't +exist, create a client named "Andy" which is not locked. -You can do the same with the `find_or_create_by` method: +We can achive this in two ways. The first is to use `create_with`: ```ruby -Client.find_or_create_by_first_name(:first_name => "Andy", :locked => false) +Client.create_with(locked: false).find_or_create_by(first_name: 'Andy') ``` -This method still works, but it's encouraged to use `first_or_create` because it's more explicit on which arguments are used to _find_ the record and which are used to _create_, resulting in less confusion overall. +The second way is using a block: -### `first_or_create!` +```ruby +Client.find_or_create_by(first_name: 'Andy') do |c| + c.locked = false +end +``` -You can also use `first_or_create!` to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add +The block will only be executed if the client is being created. The +second time we run this code, the block will be ignored. + +### `find_or_create_by!` + +You can also use `find_or_create_by!` to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add ```ruby validates :orders_count, :presence => true @@ -1272,19 +1284,21 @@ validates :orders_count, :presence => true to your `Client` model. If you try to create a new `Client` without passing an `orders_count`, the record will be invalid and an exception will be raised: ```ruby -Client.where(:first_name => 'Andy').first_or_create!(:locked => false) +Client.find_or_create_by!(first_name: 'Andy') # => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank ``` -As with `first_or_create` there is a `find_or_create_by!` method but the `first_or_create!` method is preferred for clarity. - -### `first_or_initialize` +### `find_or_initialize_by` -The `first_or_initialize` method will work just like `first_or_create` but it will not call `create` but `new`. This means that a new model instance will be created in memory but won't be saved to the database. Continuing with the `first_or_create` example, we now want the client named 'Nick': +The `find_or_initialize_by` method will work just like +`find_or_create_by` but it will call `new` instead of `create`. This +means that a new model instance will be created in memory but won't be +saved to the database. Continuing with the `find_or_create_by` example, we +now want the client named 'Nick': ```ruby -nick = Client.where(:first_name => 'Nick').first_or_initialize(:locked => false) -# => <Client id: nil, first_name: "Nick", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27"> +nick = Client.find_or_initialize_by(first_name: 'Nick') +# => <Client id: nil, first_name: "Nick", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27"> nick.persisted? # => false |