仅当 Rails 模型属性先前为空时才接受

发布于 2024-12-22 19:12:35 字数 267 浏览 0 评论 0原文

我有一个 Rails 模型(与 Mongoid 一起保留),任何注册用户都可以协作编辑它。但是,我只想允许编辑任何特定属性,前提是该属性之前为空或为零。

例如,假设某人创建了一个对象,并将其 title 属性设置为 “Test Product”。然后另一个用户出现并想要添加 price 的值,而到目前为止该值一直是 nil

在锁定先前输入的属性的同时,执行此操作的最佳方法是什么?

I have a Rails model (persisted with Mongoid) that can be collaboratively edited by any registered user. However, I want to allow editing any particular attribute only if it was previously blank or nil.

For example, say someone created an object, and set its title attribute to "Test Product". Then another user comes along and wants to add a value for price, which until now has been nil.

What's the best way to do this, while locking an attribute that has previously been entered?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少女七分熟 2024-12-29 19:12:35

查看 ActiveRecord::Dirty 模块,了解一些不错的实用方法可以用来做这样的事情:

NON_UPDATABLE_ATTRIBUTES = [:name, :title, :price]
before_validation :check_for_previously_set_attributes

private
def check_for_previously_set_attributes
  NON_UPDATABLE_ATTRIBUTES.each do |att|
    att = att.to_s
    # changes[att] will be an array of [prev_value, new_value] if the attribute has been changed
    errors.add(att, "cannot be updated because it has previously been set") if changes[att] && changes[att].first.present?
  end
end

Look into the ActiveRecord::Dirty module for some nice utility methods you can use to do something like this:

NON_UPDATABLE_ATTRIBUTES = [:name, :title, :price]
before_validation :check_for_previously_set_attributes

private
def check_for_previously_set_attributes
  NON_UPDATABLE_ATTRIBUTES.each do |att|
    att = att.to_s
    # changes[att] will be an array of [prev_value, new_value] if the attribute has been changed
    errors.add(att, "cannot be updated because it has previously been set") if changes[att] && changes[att].first.present?
  end
end
冰葑 2024-12-29 19:12:35

我认为最简单的方法是在表单本身中检查它。
只需说添加:禁用=>如果用户无法编辑输入字段,则为 true。

<% if @my_object.name %>
   <%= f.text_field :name, :disabled => true %>
<% else %>
   <%= f.text_field :name, :disabled => true %>
<% end %>    

(我认为有一种更漂亮的方法来编写这段代码)

但是通过使用这个,用户可以得到一个视觉反馈,表明他不能做某事,不分配某些东西总是比给出错误消息更好

The easiest way, i think, is by checking for it in the form itself.
Just say add :disabled => true to the input field if the person cannot edit it.

<% if @my_object.name %>
   <%= f.text_field :name, :disabled => true %>
<% else %>
   <%= f.text_field :name, :disabled => true %>
<% end %>    

(i think there is a prettier way to write this code)

But by using this the user has a visual feed back that he can't do something, it is always better to not allor something than to give an error message

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文