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

时间:2022-05-31 06:23:11

I have a database table with a certain field which should be impossible to update once it has been inserted to the database. How do I tell my model that it shouldn't allow updating of a certain field?

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

2 个解决方案

#1


45  

You want to use attr_readonly:

你想使用attr_readonly:

Attributes listed as readonly will be used to create a new record but update operations will ignore these fields.

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

class Customer < ActiveRecord::Base
    attr_readonly :your_field_name
end

#2


2  

And that field is always and by definition "correct" (i.e. an accurate representation of reality) at the time of insertion ?

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

No user ever makes a mistake when entering that field for the first (and in your scheme : only) time ?

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

#1


45  

You want to use attr_readonly:

你想使用attr_readonly:

Attributes listed as readonly will be used to create a new record but update operations will ignore these fields.

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

class Customer < ActiveRecord::Base
    attr_readonly :your_field_name
end

#2


2  

And that field is always and by definition "correct" (i.e. an accurate representation of reality) at the time of insertion ?

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

No user ever makes a mistake when entering that field for the first (and in your scheme : only) time ?

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