Ruby on Rails latest stable (v4.1.8) - 1 note - 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
1 thank

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"