Flowdock
method

first_or_create

Importance_2
Ruby on Rails latest stable (v4.2.1) - 2 notes - Class: ActiveRecord::Relation
first_or_create(attributes = nil, &block) public

No documentation

This method has no description. You can help the Ruby on Rails community by adding new notes.

Show source
Register or log in to add new notes.
November 6, 2014
6 thanks

Find the First Instance in the Table. If None Exists, Create One.

Specify the data you’re looking for. If it exists in the table, the first instance will be returned. If not, then create is called.

If a block is provided, that block will be executed only if a new instance is being created. The block is NOT executed on an existing record.

Code example

MyStat.where(name: statistic_name).first_or_create do |statistic|
  statistic.value = calculate_percentage
  statistic.statistic_type = "percentage"
end
January 22, 2016
0 thanks

Creates record by given attributes only if table is empty

This method first searches the table for ANY FIRST RECORD, not the one matching given attributes. If no record is found at all, it creates one using the specified attributes. This might be misunderstood in many cases.