2017-08-13 62 views
0

我使用Cocoon作爲嵌套窗體。對於task記錄已經創建,我想要description read_only。Rails Cocoon只讀字段

項目/ _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

+0

您目前有什麼問題? – Pavan

+0

'disabled:true''''''''''cocoon',see' else' section('= f.input:description')沒有'disabled:true' – dp7

+0

這個想法是爲記錄描述'read_only'以前已經保存過,並且在渲染「新任務」時可編輯 –

回答

1

對於已創建的任務記錄,我想將描述設置爲 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,描述的值將不會被提交,無法通過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