使用ajax操作预填充Rails collection_select(Rails 5和jQuery) [英] Pre-populate Rails collection_select with ajax action (Rails 5 and jQuery)

查看:90
本文介绍了使用ajax操作预填充Rails collection_select(Rails 5和jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个发票应用,其中每个发票都有一行发票项目(例如产品名称,成本,金额).

I am trying to build an invoice app where every invoice has a line invoice item(e.g. productname, cost, amount).

我想从发票项目的下拉列表中选择产品名称时,触发ajax来查询产品数据库表 params [:product_id] ,从数据库中获取产品成本,从而立即填充物料成本.

I want when i select productname from the from a drop-down list in the invoice item, an ajax is fired to query the product database table with params[:product_id], gets the product cost from the database and hence populate the item cost instantly.

即当用户选择产品名称时,该产品费用会立即显示出来,而无需输入.

i.e. When a user select product name, that product cost shows up too instantly without typing it.

在下面的图片中,我的query_string按预期返回JSON,除了我不知道如何将返回的数据传递/显示到 cost_field .

In the attached image below, my query_string returns JSON as expected, except for i dont know how to pass/display the returned data to the cost_field.

如果我执行 html(product.cost),则在#notification中获取/返回 [object,object] ,而在 unfind cost Rails控制台也是如此.

If i do html(product.cost), i get/return [object, object] at #notification and undefind cost in the rails console too.

我的问题是,我该怎么做? $(#notification").html(product.cost)

My question is, how do i do something like this? $("#notification").html(product.cost)

型号:

    class Invoice < ApplicationRecord
      has_many :items, dependent: :destroy
      accepts_nested_attributes_for :items, allow_destroy: true,  reject_if: proc {|a| a[:product_id].blank?}
      has_many :products, through: :item
    end

    class Item < ApplicationRecord
      belongs_to :invoice, optional: true
      belongs_to :item, optional: true
    end

    class Product < ApplicationRecord
      has_many :items
    end

CONTROLLER

   class InvoicesController < ApplicationController
      before_action :set_invoice, only: [:show, :edit, :update, :destroy]


   def index
     @invoices = Invoice.all
   end

   def new
     @invoice = Invoice.new
     2.times {  @invoice.items.build }
   end

   def pricedata
    @product = Product.select(:id, :cost, :productname).where('products.id = ?', params[:product_id])

     respond_to do |format|
     format.html {  render html: @product.id }
     format.js #{ render js: @product}
     format.json { render json: @product }
   end

  private
     def invoice_params
        params.require(:invoice).permit(:name, :amount, items_attributes: [:qty, :price, :id, :product_id, :_destroy])
     end

表格

     <p id="notification"></p>   # notice to keep my eyes on return obj

    ...

    <%= f.fields_for :items do |item| %>

     <span><%= item.label :product_id %>      </span>


     <span>       // # collection begins here
       <%= item.collection_select(:product_id, Product.all, :id, :productname,
            {prompt: "Select a product"}, 
            {class: 'selectors'  multiple: true })  
       %>
      </span>     // # collection ends here


     <span><%= item.label :qty %> </span>
     <span><%= item.number_field :qty %> </span>
     <span><%= item.label :price, class: "p_price"   %> </span>
     <span><%= item.number_field :price %> </span> 
     <span><%= item.check_box :_destroy %> Remove item</span>

    ...

JAVASCRIPT/咖啡

  $(document).ready ->
    $('.selectors').on "change", ->
    selectOptions= $('.selectors option:selected')
    product_id = $(this).val()

    if selectOptions.length > 0
        selectOptions.each ->
            $.ajax({
                url: '/invoices/:id/pricedata?product_id=' + product_id,
                type: 'GET',
                dataType: 'html',
                contentType: 'application/html'
                success: (product)-> 
                        $("#noticification").html(product)
                        console.log(product)
                    })

推荐答案

您真的过于复杂了.要获取产品的详细信息,您应该只向ProductsController上的简单show动作发送ajax请求.

You're really overcomplicating it. To get the details for a product you should just be sending an ajax request to a simple show action on ProductsController.

class ProductsController < ApplicationController
  # GET /products/:id
  def show
    @product = Product.find(params[:id])
    respond_to do |format|
     format.html
     format.json { render json: @product }
    end
  end
end

在这种情况下,您也不应该使用多重选择,因为这样会使数量和价格不明确.而是为每个项目行创建一个字段集或div. fields_for 助手可用于每个项目的特定范围:

Also you should not use a multiple select in this case as it would make the quantity and price ambiguous. Instead create a fieldset or div for each item row. The fields_for helper can be used to give a specific scope for each item:

<%= form_for(@invoice) do %>
  # ...
  <%= fields_for(:items) do |item| %>
    <!-- group each item in an element so you can find the associated inputs -->
    <div class="item">
     <!-- use a div to group inputs ands labels instead! -->
     <span><%= item.label :product_id %>      </span>
     <span><%= item.collection_select(:product_id, Product.all, :id, :productname,
            {prompt: "Select a product"}, 
            {class: 'selectors'  multiple: true })  %>
     </span>     // # collection ends here
     <span><%= item.label :qty %> </span>
     <span><%= item.number_field :qty %> </span>
     <span><%= item.label :price, class: "p_price"   %> </span>
     <span><%= item.number_field :price %> </span> 
     <span><%= item.check_box :_destroy %> Remove item</span>
    </div>
  <% end %>
  # ...
<% end %>

这篇关于使用ajax操作预填充Rails collection_select(Rails 5和jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆