我遇到了将变量从我的控制器异步传递到局部的问题。我想要发生的是在用户从下拉菜单中选择一个选项后,在我的视图上呈现一个表单。问题是我一直收到这个错误:
undefined local variable or method `shipment_options' for #<# <Class:0x007f92941be8f0>:0x007f929ca78ad8>
即使我使用像locals: { var: @var }
这样的东西。以下是我认为的代码:
<body>
<p>
This is the body<br>
<%= select_tag :service, options_for_select(usps_services), { id: "service_select", remote: true } %><br>
<div id='shipment_option'>
<%= render 'shipment_option', remote: true, locals: { shipments: @shipment_options } %>
</div>
</body>
<script>
$('#service_select').on('change', function () {
var service = $('#service_select').val();
$.ajax({
type: "POST",
url: '/service_select',
format: 'js',
data: { service: service, order_id: <%= params[:order_id] %> },
success: function (data) {
console.log(data.rates);
return true;
},
error: function (data) {
return false;
}});
});
</script>
处理该AJAX请求的路由
# AJAX
# get '/ajax/:service' => 'dashboards#get_shipment'
post '/service_select' => 'dashboards#get_shipment'
控制器中的get_shipment
方法
def get_shipment
order = Order.find(params[:order_id])
respond_to do |format|
from_address = EasyPost::Address.create(
:street1 => Rails.configuration.from_address[:street1],
:street2 => Rails.configuration.from_address[:street2],
:city => Rails.configuration.from_address[:city],
:state => Rails.configuration.from_address[:state],
:zip => Rails.configuration.from_address[:zip]
)
to_address = EasyPost::Address.create(
:name => order.name,
:street1 => order.street1,
:street2 => order.street2,
:city => order.city,
:state => order.state,
:zip => order.zip
)
parcel = EasyPost::Parcel.create(
:predefined_package => params[:service],
:weight => 10
)
@shipment_options = EasyPost::Shipment.create(
:to_address => to_address,
:from_address => from_address,
:parcel => parcel
)
# format.json { render json: ActiveSupport::JSON.encode(shipment_option) }
format.js { render json: @shipment_options, action: "new" }
end
端
我尝试渲染的部分代码
<%= form_for(@shipment) do |f| %>
<% shipment_options.rates.each do |rate| %>
<%= f.label :shipment_service %>
<%= rate.service + " " + rate.rate.to_s %>
<%= f.check_box :shipment_service %>
<% end %>
<%= f.submit "Ship package" %>
<% end %>
如何摆脱这个错误?谢谢。
答案 0 :(得分:1)
看起来您已将@shipment_options作为货件传递给您的部分货物,但在您的部分货物中,您正在调用尚未定义的shipping_options。
答案 1 :(得分:0)
好的,我通过取出控制器中format.js
的所有参数,然后将.js.erb
转换为get_shipment.js.erb
来解决问题。然后在我通过写:
@shipment_options
$('#shipment_option').html("<%= j(render 'shipment_option') %>");
然后正确呈现表单,因为我已经设置了实例变量。