Search code examples
ruby-on-railscocoon-gem

Rails Cocoon read only fields


I am using Cocoon for nested forms. For task records that are already created, I want description to be 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

And _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

Currently the validation in _task_fields is not working: undefined method <description> for nil:NilClass in the line with if statement. How can I write the IF statement correctly?


Solution

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

    You are doing it wrong. You should be able do the check by using new_record? like so

    .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
    

    Also, by using disabled: true, the value of description won't be submitted and cannot be passed through params. If you want to have the description value in the params, use readonly: true instead.

    .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