防止更改 Rails 模型中的一个字段 [英] Prevent change of one field in Rails model

查看:36
本文介绍了防止更改 Rails 模型中的一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相关的模型 - 比如说 ActivityStep.Activity has_many :stepsStepbelongs_to :activity 这意味着 steps 的表有一个 activity_id 列.>

这是在 Hobo 1.3 中,所以在 Rails 3.0 中.

我想要的是确保Step创建之后,不可能将一个步骤移动到另一个Activity.我们不希望 activity_id 字段发生变化.

我已从编辑表单中删除了该字段,但我正在寻找更强的约束条件.本质上,我想在 update(而不是 create)上验证该列没有被触及.Hobo 的文档没有暗示 Hobo 内部的任何类型,所以我正在查看 Rails 验证,但到目前为止,我还没有找到我记得的仅在更新时执行此操作"约束,也没有验证某些内容没有改变.

解决方案

您可以使用 attr_readonly :your_field_name 将属性声明为只读.但是,如果您尝试编写此属性,这不会产生错误,它会静默失败.(所有 SQL 更新都会忽略此属性)

另一种选择可能是,为此案例编写验证,可能如下所示:

class Step 

persisted? 返回真,如果这不是新记录并且没有被销毁.

链接:

http://api.rubyonrails.org/classes/ActiveRecord/ReadonlyAttributes/ClassMethods.html#method-i-readonly_attributes

http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-persisted-3F

I have two related models - let's say Activity and Step. Activity has_many :steps and Step belongs_to :activity which means the table for steps has an activity_id column.

This is in Hobo 1.3, so Rails 3.0.

What I want is to ensure that after Step creation it is not possible to move a step to another Activity. We don't want the activity_id field to change.

I've removed the field from edit forms, but I'm looking for a stronger constraint. Essentially I want to validate on update (not on create) that the column isn't being touched. Hobo's documentation doesn't suggest anything of the sort inside Hobo, so I'm looking at Rails validations, but so far I haven't found the "only do this on update" constraint that I remember, nor a validation that something isn't changing.

解决方案

You can declare an attribute as read_only with attr_readonly :your_field_name. But this won't create an error if you try to write this attribute, it will fail silently. (This attribute will be ignored for all SQL-Updates)

Another option might be, to write a validation for this case, might look like this:

class Step < ActiveRecord::Base
  validate :activity_id_not_changed

  private

  def activity_id_not_changed
    if activity_id_changed? && self.persisted?
      errors.add(:activity_id, "Change of activity_id not allowed!")
    end
  end
end

persisted? returns true, if this is not a new record and it is not destroyed.

Links:

http://api.rubyonrails.org/classes/ActiveRecord/ReadonlyAttributes/ClassMethods.html#method-i-readonly_attributes

http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-persisted-3F

这篇关于防止更改 Rails 模型中的一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆