【发布时间】:2011-04-27 10:41:27
【问题描述】:
我使用Ryan's method 使用jQuery 通过JavaScript 动态添加和删除嵌套模型字段。
有4个模型:client、c_person;项目,p_person。以及一对多的关联:client 有很多 c_people,project 有很多 p_people(这些是 client 方的人,但他们属于 project)。
所以,我有以下问题:
当我在视图中使用辅助方法“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>
这是获取 current_client_id 值的简单 js 函数,但我不知道如何将它传递给我的视图或辅助方法。
// application.js
function current_client_id() {
var current_client_id = $("select#client_id :selected").val();
}
感谢您的帮助!也许有更好的解决方案?
【问题讨论】:
标签: javascript jquery ruby-on-rails ruby-on-rails-3 parameter-passing