使用ajax操作预先填充Rails collection_select(Rails 5和jQuery)

时间:2016-11-20 21:07:34

标签: javascript jquery ruby-on-rails ruby-on-rails-5

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

我希望当我从发票项目的下拉列表列表中选择 productname 时,会触发ajax来查询产品数据库表< / strong>使用 params [:product_id] ,从数据库中获取产品成本,从而立即填充项目成本。

即。当用户选择产品名称时,该产品成本会立即显示而无需输入。

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

如果我 html(product.cost),我会在#notification和取消发现费用中获取/返回 [object,object] rails控制台也是。

我的问题是,我该如何做这样的事情? $(&#34;#通知&#34)。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

FORM

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

  $(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)
                    })

enter image description here

1 个答案:

答案 0 :(得分:0)

你真的过于复杂了。要获取产品的详细信息,您只需向ProductsController上的简单展示操作发送ajax请求即可。

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

在这种情况下,您不应该使用多重选择,因为它会使数量和价格模糊不清。而是为每个项目行创建一个fieldset或div。 fields_for帮助器可用于为每个项目提供特定范围:

<%= 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 %>