Hi, I'm using Ryan's solution to add and remove nested model fields dynamically through JavaScript using jQuery.
There are 4 models: client, c_person; project, p_person. And one-to-many associations: client has many c_people and project has many p_people (these are people from client side but they belongs to project). Hope it isn't too complicated example)
So, I have following problem, please help:
When I'm using helper method "link_to_add_fields" in my view, I need to pass another parameter (current_client_id) that depends of what client is currently selected in select box.
<!-- new.html.erb -->
<p>
<%= f.label :client_id %></br>
<%= f.collection_select :client_id, Client.order("title"), :id, :title %>
</p>
<p>
<%= f.fields_for :p_people do |builder| %>
<%= render "p_person_fields", :f => builder %>
<% end %>
</p>
<p><%= link_to_add_fields "Add Person", f, :p_people, current_client_id %></p>
I need that to dynamically change the collection for @people variable in helper method,
# application_helper.rb
def link_to_add_fields(name, f, association, current_client_id)
new_object = f.object.class.reflect_on_association(association).klass.new
@people = CPerson.where(:client_id => current_client_id).order(:name) unless current_client_id.blank?
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
to finally use it in partial:
<!-- _p_person_fields.html.erb -->
<div class="fields">
<p>
<%= f.collection_select :content, @people, :name, :name %>
<%= f.hidden_field :_destroy %>
<%= link_to_function "Remove", "remove_fields(this)" %>
</p>
</div>
I've implemented simple js function to get current_client_id value, but I don't know how to pass it to my view or helper method.
// application.js
function current_client_id() {
var current_client_id = $("select#client_id :selected").val();
}
I appreciate your help! Maybe there is a better solution?