Rails Cocoon 只读字段

Rails Cocoon read only fields

我将 Cocoon 用于嵌套表单。对于已经创建的 task 条记录 ,我希望 description 为 read_only。

projects/_form::

= simple_form_for @project do |f|
  = f.input :name
  = f.input :description
  %h3 Tasks
  #tasks
    = f.simple_fields_for :tasks do |task|
      = render 'task_fields', f: task
    .links
      = link_to_add_association 'add task', f, :tasks
  = f.submit

和_task_fields:

.nested-fields
  - if @task.description?
    = f.text_field :description, disabled: true
  - else
    = f.input :description
    = f.input :done, as: :boolean
  = link_to_remove_association "remove task", f

目前 _task_fields 中的验证无效:undefined method <description> for nil:NilClassif 语句行中。我怎样才能正确地写 IF statement

For task records that are already created, I want description to be read_only.

你做错了。您应该可以像这样

使用 new_record? 进行检查
.nested-fields
  - unless f.object.new_record?
    = f.text_field :description, disabled: true
  - else
    = f.input :description
    = f.input :done, as: :boolean
  = link_to_remove_association "remove task", f

另外,使用disabled: true,description的值不会被提交,也无法通过params传递。如果您想在 params 中使用描述值,请改用 readonly: true

.nested-fields
  - unless f.object.new_record?
    = f.text_field :description, readonly: true
  - else
    = f.input :description
    = f.input :done, as: :boolean
  = link_to_remove_association "remove task", f