Form for array element in partial
I'm making a project for which I have a class online_score
which has as one of its attributes an array called url
of online_score_url
objects. What I did up to now is the following.
views/online_score/new:
<div class="urlInput">
<% f.fields_for :url do |b| %>
<%= render "online_score_url_fields", :f => b %>
<% end %>
<%= add_url_link "Add Another link", f %>
</div>
views/online_score/_online_score_url_fields:
<div class="inputset">
<%= f.label :url %> <%= f.url_field :url, :value => "http://www.goo开发者_如何学Pythongle.be"%>
<%= f.label :description %> <%= f.text_field :description %>
<%= link_to_remove_fields "remove", f %>
</div>
My problem is now that I want to be able to dynamically add inputs for online_score_url
objects which I try to do with JQuery. I try to do this by rendering the partial like so:
helpers/online_scores_helper.rb:
def add_url_link(name, form)
link_to_function name do |page|
online_score_url = render(:partial => 'online_score_url_fields', :f => form )
page << %{
$('.links').append("#{ escape_javascript online_score_url }");
}
end
end
The problem is then that f
seems to be undefined in the partial. I expect this has something to do with the line <% f.fields_for :url do |b| %>
in my view which doesn't get executed via the dynamic adding. But I don't really know how to fix. I think I need an alternative for the form_for
method? How to do that?
I guess my main question is: how do I iterate over an array in a controlled way, and for every element create a set of input forms like in the partial AND be able to 'add' one or more dynamically?
Thanks for your time.
Try this one:
<%= render "online_score_url_fields", :locals => {:f => b} %>
this is beacuse :f is not a parameter for the render method. So you need to use :object, :collection or something locals with the syntax above.
The same here:
online_score_url = render(:partial => 'online_score_url_fields', :locals => {:f => form} )
精彩评论