Reputation: 84170
I have the following model:
class Deck < ActiveRecord::Base
has_many :cards
serialize :stats
attr_accessible :name, :description, :stats
end
In this, stats should be an array of strings. I want to be able to add an arbitrary number of stats to the row (using javascript to add additional "stat" input boxes, but that is outside the scope if the question.)
My question is how do I reflect this structure in the view? If I was building the form manually then it would look like:
<input type="text" name="deck[stats][]">
My view currently looks like:
<%= f.fields_for :stats, @deck.stats do |p| %>
<%= p.label :p, "Stats: " %>
<%= p.text_field :p %>
<% end %>
But this outputs:
<input type="text" name="deck[stats][p]">
I also want a counter so I can display the label as "Stat 1:", "Stat 2:", etc.
Any help is appreciated.
Upvotes: 1
Views: 2676
Reputation: 677
= simple_form_for [:stats, @deck] do |f|
- 1.upto(4) do |i|
= f.input_field :stats, multiple: true, label: "Stat #{i}"
= f.submit
Upvotes: 0
Reputation: 84170
Posting the solution I went for to aid future readers.
#Controller
def new
@deck = Deck.new
@deck.stats = ["", ""] #include for number of times you wish to show the field.
end
#View
<%@deck.stats.each_with_index do |s,i| %>
<p>
Stat <%=i+1%>: <%=text_field "stat", i, :name => "deck[stats][]", :value => s %>
</p>
<%end%>
Upvotes: 1
Reputation: 7714
I don't know if there's a clean way of doing it, but this should work:
<% @deck.stats.each do |value|
<%= f.fields_for :stats do |fields| %>
<%= fields.text_field "", :value => value %>
<% end %>
<% end %>
Upvotes: 0
Reputation: 9216
By defining :p
you are making it think you are looking for a method on stats called p, ie stats.p
<%= f.fields_for :stats, @deck.stats do |p| %>
<%= p.label :p, "Stats: " %>
<%= p.text_field :p %>
<% end %>
Rather just try <%= p.text_field %>
drop the :p
Upvotes: 0