dee*_*raj 9 jquery ruby-on-rails getjson nested-forms ruby-on-rails-3.2
我正在尝试以下方面.主窗体中的客户选择选项.当用户选择主表单中的客户时,他的账单应出现在所有后续部分中.
我正在使用ryan bates的nested_form gem来获取部分内容.代码如下.
<%= simple_nested_form_for @money_receipt do |f| %>
<div class="customers"><%= f.collection_select :customer_id, Customer.all, :id, :name, options ={:prompt => "-Select a Customer"}, :style=>'width:210px;'%></div><br />
/*rest of the code*/
<%= f.link_to_add "Add line items", :money_receipt_line_items %>
Run Code Online (Sandbox Code Playgroud)
在局部内部
<div class="bill">
<%= f.collection_select :customer_bill_id, CustomerBill.all,:id,:id, {:prompt => "Select Customer bill"}, :style => 'width:202px;' %></div><br />
/*rest of the code*/
Run Code Online (Sandbox Code Playgroud)
上面的jQuery代码如下
jQuery(document).ready(function(){
jQuery(".customers select").bind("change", function() {
var data = {
customer_id: jQuery(this).val()
}
jQuery.getJSON(
"/money_receipts/get_bills",
data, function(data){
var result = "",a,x;
var b = "<option>Select customer Bill</option>"
for(i=0;i<data.length; i++)
{
a = data[i];
result = result + "<option value="+a[0]+">"+a[0]+"</option>";
console.log(result);
}
child=jQuery('.bill select').html(b+result);
});
});
});
Run Code Online (Sandbox Code Playgroud)
最后在控制器中我有.def get_bills
@bill_amount = CustomerBill.find_all_by_customer_id(params[:customer_id]).map{|bill| [bill.id]} if params[:customer_id]
respond_to do |format|
format.json { render json: @bill_amount }
end
end
Run Code Online (Sandbox Code Playgroud)
我试图过滤账单并输入div id bill.现在,如果我console.log在jQuery代码中执行,我将获得customer_id和账单,但我无法发布它.如果我做console.log的child,我得到的输出,因为这jQuery().我哪里错了?是否有更好的方法来实现上述目标?需要指导.提前致谢.
小智 7
我个人更喜欢将HTML放入partials而不是用JS代码绘制的方式.
像这样:
money_receipt.js:
$('.customers select').change(function(){
$.getScript('/money_receipts/get_bills?customer_id='+$(this).val())
})
Run Code Online (Sandbox Code Playgroud)
get_bills.js.erb:
$('.bill select').html('<%=j render 'get_bills'%>')
Run Code Online (Sandbox Code Playgroud)
_get_bills.html.erb:
<% @bills.each do |bill| %>
<option value="<%=bill.id%>"><%=bill.title%></option>
<% end %>
Run Code Online (Sandbox Code Playgroud)
使用较少的代码行可以减少错误发生的位置.