Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails reusing form view on edit, but setting some fields readonly

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. :)

like image 856
gaqzi Avatar asked Nov 06 '22 13:11

gaqzi


1 Answers

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?
like image 175
Pete Avatar answered Nov 11 '22 04:11

Pete