1

I have a form field where a user inputs a string of tags "foo, bar, foobar". This is sent to the controller as item_params[:tag_list]. In the controller my create action includes @item = Item.create(tag_list: item_params[:tag_list]). This causes the tag_list attribute to be populated as an array of strings ["foo", "bar", "foobar"].

When validation fails I need the input field of the form to be populated with "foo, bar, foobar" and not the array of strings. Is there a way to manipulate this before it goes back to populate the field of the form that failed validation?

1
  • what is the validation? Commented Jan 30, 2016 at 6:01

2 Answers 2

0

Are you using acts-as-taggable-on gem? Hope this line can resolve you problem

f.text_field :tag_list, value: f.object.tag_list.join(', ')

Or you have to override tag_list method in Item model

alias_method :array_tag_list, :tag_list
def tag_list
  array_tag_list.join(', ')
end
Sign up to request clarification or add additional context in comments.

2 Comments

I wasn't able to get your suggestion to work. It might be because I am using bootstrap tag inputs and it is causing a problem. I was able to solve my problem by changing the tag_list attribute to a string if the validation fails. I did this in the controller @item.tag_list.remove(item_params[:tag_list], parse: true) then @item.tag_list.add(item_params[:tag_list])
I think you have to override tag_list method in Item model. alias_method :array_tag_list, :tag_list def tag_list array_tag_list.join(', ') end
0

Highly surprised that the param is being treated as an array.


Sorry, misread your question (presumed you wanted validation message). Will leave for posterity:

Whenever you use a validation, you get access to three interpolations: value, attribute & model:

#app/models/item.rb
class Item < ActiveRecord::Base
   validates :tag_list, x: { message: "%{value} is not valid" }
end

According to the docs, you can pass a Proc for direct manipulation:

#app/models/item.rb
class Item < ActiveRecord::Base
   validates :tag_list, x: { message: ->(key, data) do
       "#{data[:value].join} is not valid"
    end 
   }
end

--

In order to populate the field, you'll want to use the value attribute of the attribute, populating with data from the form object:

= text_field :tag_list, value: f.object.tag_list.join

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.