first_or_create(attributes = nil, &block)public
# File activerecord/lib/active_record/relation.rb, line 153 def first_or_create(attributes = nil, &block) # :nodoc: first || create(attributes, &block) end
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.
MyStat.where(name: statistic_name).first_or_create do |statistic| statistic.value = calculate_percentage statistic.statistic_type = "percentage" end
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.