跳至内容 跳至搜索
方法
A
R

实例公共方法

attr_readonly(*attributes)

列出的 Attributes 将被用作创建新记录。在已持久化的记录上为只读属性分配新值会引发错误。

通过将 config.active_record.raise_on_assign_to_attr_readonly 设置为 false,将不会引发错误。值将在内存中更改,但不会在 save 时持久化。

示例

class Post < ActiveRecord::Base
  attr_readonly :title
end

post = Post.create!(title: "Introducing Ruby on Rails!")
post.title = "a different title" # raises ActiveRecord::ReadonlyAttributeError
post.update(title: "a different title") # raises ActiveRecord::ReadonlyAttributeError
# File activerecord/lib/active_record/readonly_attributes.rb, line 30
def attr_readonly(*attributes)
  self._attr_readonly |= attributes.map(&:to_s)

  if ActiveRecord.raise_on_assign_to_attr_readonly
    include(HasReadonlyAttributes)
  end
end

readonly_attributes()

返回一个包含所有被指定为只读的属性的数组。

# File activerecord/lib/active_record/readonly_attributes.rb, line 39
def readonly_attributes
  _attr_readonly
end