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.

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top