【问题标题】:Rails Cocoon read only fieldsRails Cocoon 只读字段
【发布时间】:2017-08-13 17:25:04
【问题描述】:

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

项目/_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:NilClass 与if 语句一致。如何正确写IF statement?

【问题讨论】:

  • 您目前遇到了什么问题?
  • disabled: true 应该与Cocoon 一起使用,我看到else 部分(= f.input :description)没有disabled: true
  • 这个想法是为之前保存的记录提供描述read_only,并且在呈现“新任务”时可编辑

标签: ruby-on-rails cocoon-gem


【解决方案1】:

对于已经创建的任务记录,我希望描述为 只读。

你做错了。您应该可以像这样使用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

【讨论】:

    猜你喜欢
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多