如何在Rails中使数据库字段为只读?

问题描述 投票:20回答:3

我有一个带有某个字段的数据库表,一旦插入数据库就不可能更新。如何告诉我的模型它不应该允许更新某个字段?

ruby-on-rails rails-activerecord
3个回答
50
投票

你想使用attr_readonly

列为readonly的属性将用于创建新记录,但更新操作将忽略这些字段。

class Customer < ActiveRecord::Base
    attr_readonly :your_field_name
end

2
投票

在插入时,该字段总是按照定义“正确”(即现实的准确表示)?

在第一个(并且在你的方案中:仅)时间输入该字段时,没有用户犯过错误?


0
投票

这是我对类似问题的相关解决方案 - 我们希望用户能够自己设置字段,我们在创建记录时不需要它们,但我们不希望它们在设置后进行更改。

  validate :forbid_changing_some_field, on: :update

  def forbid_changing_some_field
    return unless some_field_changed?
    return if some_field_was.nil?

    self.some_field = some_field_was
    errors.add(:some_field, 'can not be changed!')
  end

令我感到惊讶的是,update_attribute仍然有效,它绕过了验证。这并不是什么大不了的事,因为记录的更新在实践中被大量分配 - 但我在测试中称之为明确。这是一些测试。

    describe 'forbids changing some field once set' do
      let(:initial_some_field) { 'initial some field value' }
      it 'defaults as nil' do
        expect(record.some_field).to be nil
      end

      it 'can be set' do
        expect {
          record.update_attribute(:some_field, initial_some_field)
        }.to change {
          record.some_field
        }.from(nil).to(initial_some_field)
      end

      describe 'once it is set' do
        before do
          record.update_attribute(:some_field, initial_some_field)
        end

        it 'makes the record invalid if changed' do
          record.some_field = 'new value'
          expect(record).not_to be_valid
        end

        it 'does not change in mass update' do
          expect {
            record.update_attributes(some_field: 'new value')
          }.not_to change {
            record.some_field
          }.from(initial_some_field)
        end

        it 'DOES change in update_attribute!! (skips validations' do
          expect {
            record.update_attribute(:some_field, 'other new value')
          }.to change {
            record.some_field
          }.from(initial_some_field).to('other new value')
        end
      end
    end
© www.soinside.com 2019 - 2024. All rights reserved.