jquery - jQuery 对 ruby​​ on Rails 中的部分数据执行的默认操作

标签 jquery ruby-on-rails ruby-on-rails-3.2 nested-forms getjson

我正在尝试以下操作。 主窗体中的客户选择选项。当用户在主窗体中选择客户时,他的账单应出现在所有后续部分中。

我正在使用 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 %>

在部分内

<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*/

上面的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);
    });
    });
  });

最后在我的 Controller 中。 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

我试图过滤账单并放入 div id bill。现在,如果我在 jQuery 代码中执行 console.log,我将获得 customer_id 和账单,但我无法发布它。如果我在 child 上执行 console.log,我会得到这样的输出 jQuery()。我哪里出错了?有没有更好的方法来实现上述目标?需要指导。提前致谢。

最佳答案

我个人更喜欢将 HTML 放入局部的方式,而不是用 JS 代码绘制。

像这样:

money_receipt.js:

$('.customers select').change(function(){
  $.getScript('/money_receipts/get_bills?customer_id='+$(this).val())
})

get_bills.js.erb:

$('.bill select').html('<%=j render 'get_bills'%>')

_get_bills.html.erb:

<% @bills.each do |bill| %>
<option value="<%=bill.id%>"><%=bill.title%></option>
<% end %>

代码行数越少,出现错误的地方就越少。

关于jquery - jQuery 对 ruby​​ on Rails 中的部分数据执行的默认操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13853248/

相关文章:

ruby-on-rails - Rails 协会 : One way associations

ruby-on-rails-3.2 - ElasticSearch与ThinkingSphinx的替代语法

ruby-on-rails - 邀请用户加入 Rails 应用组

twitter-bootstrap - Twitter Bootstrap 在使用 <th> 而不是 <td> 时不会更改颜色表标题行的颜色

javascript - 主干模型 : Ajax request in parse override

jQuery:创建并提交带有文件上传的表单

ruby-on-rails - ActiveAdmin:如何覆盖索引 Controller 操作:nil:NilClass 的未定义方法 `base'

ruby-on-rails - 使用 RSpec 和 Factory Girl 测试设计

JavaScript 成员函数和 main 函数的模式相同吗?

jquery - 如何使用循环简化此代码