方法
實體公共方法
attribute(name, cast_type = nil, default: nil, **options) 鏈結
在模型中定義一個屬性。除了屬性名稱以外,也可以指定強制類型和預設值,以及由給定的強制類型所支援的任何選項。
class Person
include ActiveModel::Attributes
attribute :name, :string
attribute :active, :boolean, default: true
end
person = Person.new
person.name = "Volmer"
person.name # => "Volmer"
person.active # => true
原始碼: 顯示 | 在 GitHub 上
# File activemodel/lib/active_model/attributes.rb, line 59 def attribute(name, ...) super define_attribute_method(name) end
attribute_names() 鏈結
傳回屬性名稱陣列為字串。
class Person
include ActiveModel::Attributes
attribute :name, :string
attribute :age, :integer
end
Person.attribute_names # => ["name", "age"]
原始碼: 顯示 | 在 GitHub 上
# File activemodel/lib/active_model/attributes.rb, line 74 def attribute_names attribute_types.keys end
type_for_attribute(attribute_name, &block) 鏈結
傳回指定屬性的類型,並套用任何修改器。這個方法是關於模型屬性的類型相關資訊唯一有效的訊息來源。這個方法的傳回值會實作 ActiveModel::Type::Value
所描述的介面(儘管這個物件本身可能不會繼承它)。
原始碼: 在 GitHub 上
# File activemodel/lib/active_model/attributes.rb, line 79