执行此操作的“标准”方式是通过 ajax(只需向您的 users#show 操作发送 JSON 请求,它应该会返回您请求的用户数据——我稍后会写)。
从你的问题看来,你应该做点别的。
用数据库中现有的客户信息填写买家信息
这是不好的做法——它会导致你的数据库中出现重复的条目。
这样做的方式是利用 Rails 中的 associations 允许您将customer 与新的买家信息关联:
#app/models/order.rb
class Order < ActiveRecord::Base
belongs_to :customer #-> requires "customer_id" in "orders" table
end
#app/models/customer.rb
class Customer < ActiveRecord::Base
has_many :orders
end
这将在您的order 上创建一个关联的customer 对象:@order.customer,它将返回您其他数据库表中的数据。
您必须确保为新的 Order 对象填充 customer_id 参数:
#app/controllers/orders_controller.rb
class OrdersController < ApplicationController
def new
@customers = Customer.all
@order = Order.new
end
def create
@order = Order.new order_params
@order.save
end
private
def order_params
params.require(:order).permit(:customer_id, :etc, :etc)
end
end
#app/views/orders/new.html.erb
<%= form_for @order do |f| %>
<%= f.collection_select :customer_id, @customers, :id, :name %>
<%= f.submit %>
<% end %>
JS
您也可以通过上述代码使用您所要求的内容。
您基本上需要向您的 customers#show 操作发送 Ajax (JSON) 请求,这会将特定 customer 的相关字段返回给您的 JS:
#app/controllers/customers_controller.rb
class CustomersController < ApplicationController
respond_to :json, :html, only: :show
def show
@customer = Customer.find params[:id]
respond_with @customer
end
end
#app/assets/javascripts/application.js
$(document).on("change", "select#customer_id", function(e){
$.ajax({
url: "customers",
dataType: "json",
data: { id: $(this).val() },
success: function(data){
// Output returned data in form
}
});
});