Rails 在编辑时重用表单视图,但将某些字段设置为只读

发布于 2024-08-30 17:15:25 字数 601 浏览 7 评论 0 原文

我有一个模型,用户在初始创建后不允许更新大多数字段。

我已经看到了 :readonly HTML 属性,我可以在所有字段帮助器上添加,但是在所有字段上执行条件感觉......很恶心。

目前我没有使用任何特殊的东西来创建我的表单,只是简单的 HAML。有人知道更好的方法吗?

这就是我到目前为止要做的事情:

def set_readonly?(object, html_attr)
  html_attr.merge(object.new_record? ? {} : {:readonly => 'readonly'})
end

用作:

f.text_field :supplier_id, set_readonly?(@damaged_goods, {:size => 5})

让我流口水的解决方案将是一种将属性与状态机 然后将传播到视图。 :)

I've a model that the user isn't allowed to update most fields on after the initial creation.

I've seen the :readonly HTML attribute I can tack on all field helpers, but doing conditionals on all fields feels... icky.

I'm not using anything special for creating my forms at the moment, just plain HAML. Anyone know of a better way of doing this?

This is what I've thought of doing it so far:

def set_readonly?(object, html_attr)
  html_attr.merge(object.new_record? ? {} : {:readonly => 'readonly'})
end

Used as:

f.text_field :supplier_id, set_readonly?(@damaged_goods, {:size => 5})

The solution to make me drool would be a way to set an attribute as read-only on the model together with State Machine which then would propagate to the views. :)

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

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

发布评论

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

评论(2

眸中客 2024-09-06 17:15:25

以下是禁用 字段的一种方法,而无需在 newedit 视图中复制表单助手:

f.text_field :supplier_id, readonly: f.object.persisted?

Here's one way to disable an <INPUT> field without duplicating your form helper in your new and edit views:

f.text_field :supplier_id, readonly: f.object.persisted?
千年*琉璃梦 2024-09-06 17:15:25

使用 attr_protected (来自 比尔·艾森豪尔)。

第一个结果来自谷歌搜索rails Constants

Use attr_protected (from Bill Eisenhauer).

1st result from Googling rails constants.

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