我使用通过使用jQuery的JavaScript动态添加和删除嵌套的模型字段。将变量值形式的js函数传递给rails视图(动态选择)
有4种型号:client,c_person;项目,p_person。和一对多的关联:客户有很多c_people,项目有很多p_people(这些是来自客户端的人,但他们属于项目)。
所以,我有以下问题:
当我使用在我看来helper方法“link_to_add_fields”,我需要通过另一个参数(current_client_id)那要看什么客户在选择框中当前选定。
<!-- 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>
我需要动态改变的集合中的辅助方法@people变量,
# 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
,终于用它在部分:
<!-- _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>
下面是简单的JS功能获取current_client_id值,但我不知道如何将它传递给我的视图或帮助器方法。
// application.js
function current_client_id() {
var current_client_id = $("select#client_id :selected").val();
}
我感谢您的帮助!也许有更好的解决方案?