instance method []

Ruby on Rails 4.1.16

Since v4.0.13

Available in: v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

[](attr_name)

Returns the value of the attribute identified by attr_name after it has been typecast (for example, “2004-12-12” in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises ActiveModel::MissingAttributeError if the identified attribute is missing.

Alias for the read_attribute method.

class Person < ActiveRecord::Base
  belongs_to :organization
end

person = Person.new(name: 'Francesco', age: '22')
person[:name] # => "Francesco"
person[:age]  # => 22

person = Person.select('id').first
person[:name]            # => ActiveModel::MissingAttributeError: missing attribute: name
person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id

Parameters

attr_name req
Source
# File activerecord/lib/active_record/attribute_methods.rb, line 382
    def [](attr_name)
      read_attribute(attr_name) { |n| missing_attribute(n, caller) }
    end

Defined in activerecord/lib/active_record/attribute_methods.rb line 382 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::AttributeMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close