Question

I'm trying to use the same HAML partial for both new and edit actions, as well as set default values in the form if it's a new action. However using something like:

= f.text_field :card_name, value: "Chase"

overrides the stored value for the record when the edit action is rendered. What is the best way to fix this without either having two separate views – one for new and one for edit – or having an ugly if/else block?

Another requirement is that the value is actually displayed in the form, so simply setting it in the controller is not an option.

Was it helpful?

Solution

What about

= f.text_field :card_name, value: (f.object.new_record? ? 'Chase' : f.object.card_name)

To get the conditional gone I'd try to do this via an ActiveRecord after_initialize.

OTHER TIPS

You could also do:

= f.text_field card_name, value: (f.object.card_name.blank? ? "Chase" : f.object.card_name)

With this approach the field only will be set, if the card_name is blank. If you for example set the card_name to "something" in the new action and there is an error caused of an other field, the card_name still will be "something" and not "Chase" again. And if the field is already set in the edit action - the value of the object will be shown.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top