【发布时间】:2018-09-19 00:31:47
【问题描述】:
我有一个呈现部分“表单”的表单。
= form_for(@booking, :as => :booking, :url => admin_bookings_path, :html => { :multipart => true }) do |f|
= render partial: "form", locals: { f: f }
在部分表单中,另一个部分再次基于 new_record 呈现?
- if f.object.new_record?
#extra-products
= render partial: 'new_booking_extra_product', locals: { f: f }
- else
= render partial: 'extra_product', locals: { f: f }
在 bookings#new 中,当用户选择特定的 car_id 时,我想通过 ajax 显示与之相关的产品。为此,我使用 ajax 向 bookings#fetch_extra_product 发出请求。
# Ajax request to fetch product
$('#booking_car_id').on('change', function(e){
var selectedCarId = $("#booking_car_id option:selected").val();
var url = "/admin/bookings/" + selectedCarId + "/fetch_extra_product";
$.ajax(url,{
type: 'GET',
success: function(msg){
},
error: function(msg) {
console.log("Error!!!");
}
});
});
# Bookings#fetch_extra_product
def fetch_extra_product
@car_id = params[:car_id] || Car.all.order('id desc').first.id
@extra_product = Car.find(@car_id).extra_products
respond_to do |format|
format.js
end
end
fetch_extra_product.js.erb 如下所示:
$('#extra-products').html('$("<%= j render(:partial => 'new_booking_extra_product', :locals => {:f => f}) %>")');
但表单对象 (f) 在此状态下未定义。获取对象或解决此问题的最佳方法是什么?
【问题讨论】:
-
你能用
_new_booking_extra_product.html.erb code更新问题吗? -
这是未定义的,因为您正在从客户端执行 ajax 请求。 'f' 对象仅在第一次请求期间存在于服务器端。
标签: javascript ruby-on-rails ruby ajax ruby-on-rails-5