KarelV
KarelV

Reputation: 507

Generate form for array with hashes with formtastic

I'm having difficulty with formtastic. I'll first try to sketch the situation as good as I can.

I have a model named onlinescore which has attributes publisher, id, and some other basic ones. One of its attributes however is an array with urls. Those urls are hashes with content like this:

{"url" => "http://www.example.com", "description" => "blabla"}

So the array looks like this:

[{"url" => "http://www.example0.com", "description" => "blabla0"},
{"url" => "http://www.example1.com", "description" => "blabla1"},
{"url" => "http://www.example2.com", "description" => "blabla2"}]

I'm now making a form to create a new onlinescore and for that I need a way to collect input for that array. I'd like to have 2 fields ("url" and "description") who get mapped into the urls array somehow. Once that works, I would want the user to be able to add several urls at once, for example with an 'add new url' button which generates another 2 of those fields.

I already tried to accomplish this on some ways for example like this:

#rest of form
<% @onlinescore.url.each do |link| %>
  <% form.inputs :for => link do |urls| %>
    <%= urls.input :url, :as => :url %>
    <%= urls.input :description, :as => :string %>
  <% end %>
<% end %>
#rest of form

which gives the error:

undefined method `model_name' for Hash:Class

I also tried to define a new input type :score_url but I didn't get far with that either because I need a tuple of 2 fields, not one and I didn't find a way to do that yet. I looked into forms without a model, but I don't really think that is what I need either...

Does anyone have an idea how to do this?

Upvotes: 1

Views: 1520

Answers (1)

Justin French
Justin French

Reputation: 2865

The main problem here (and the cause of the 'undefined method `model_name' for Hash:Class' error) is that each url you're trying to create a set of fields for is a Hash, not an ActiveRecord or ActiveModel model. If you could represent those items as an array of models, instead of an array of hashes, I think you'd be fine. Formtastic works best with models. Rails is a framework that does the same. A Hash will not work here sorry, there's too much Formtastic and Rails expect to be able to call on each item.

Upvotes: 1

Related Questions