我试图建立一个发票的应用程序,每一个发票有一行发票项目(例如产品名称,价格,数量) collection_select。预填充的Rails使用Ajax动作(导轨5和jQuery)
我想,当我从从下拉列表中发票项目选择产品名称,一个Ajax是被炒到查询产品数据库表与PARAMS [:PRODUCT_ID],得到产品成本从数据库中,因此立即填充项目成本。
即当用户选择产品名称时,该产品成本即使没有输入也会立即显示。
在下面的附加图像,我的QUERY_STRING返回JSON如预期,除了我不知道如何传递/显示返回数据到cost_field。
,如果我做HTML(product.cost),我得到/返回[目标,对象]在#notification和undefind成本导轨控制台了。
我的问题是,我该如何做这样的事情? $( “#通知”)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
控制器
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 /咖啡
$(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)
})
继@Max建议,我能解决这个问题。我直接向** ProductController **发送了一个AJAX请求。 $ .ajax HTML(产品。成本) }) –