Richlewis Richlewis - 1 year ago 78
Ruby Question

Persist data in text field after form validation fails - Active Admin

I have a text field that I pre populate with some text, but I am finding if the form validation fails then any extra text I have added is not persisted

f.input :description, as: :text, input_html: { rows: 10, cols: 10, value: bike_description }

def bike_description
"text here"

So if i added to the text field and it read
text here and some more text
, upon form validation failure the filed would just read
text here

How could i get this to remember any extra text I added, or would i load the default text in another way ?

I have tried putting this method in my model

def bike_description
read_attribute(:description).presence || 'text here'

But i get

undefined local variable or method `bike_description' for #<ActiveAdmin::Views::ActiveAdminForm:0x007fe9cb2d13a8>


Answer Source

Currently you use the return value of the bike_description method as the value for the form field. No matter how description is set on the model, bike_description will be shown.

Assuming your database has a description, than you can add a default text to the attribute reader by adding a method like this to your model:

# remove the overwritten value getter from the form
f.input :description, as: :text, input_html: { rows: 10, cols: 10 }

# add this to your model
def description
  read_attribute(:description).presence || 'text here'

This will return the current value of the description attribute or the default text if the description text is blank.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download