Rails first_or_create ActiveRecord method

前端 未结 4 494
你的背包
你的背包 2021-02-05 01:53

What does the first_or_create / first_or_create! method do in Rails?

According to the documentation, the method \"has no description\"

4条回答
  •  青春惊慌失措
    2021-02-05 02:34

    From the Guides

    first_or_create

    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.

    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:

    Client.where(:first_name => 'Andy').first_or_create(:locked => false)
    # => #
    

    The SQL generated by this method looks like this:

    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')
    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.

    first_or_create!

    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

    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:

    Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
    # => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
    

提交回复
热议问题