I am facing an issue with passing a variable from my controller to a partial asynchronously. My goal is to render a form on my view after the user selects an option from a drop-down menu. However, I keep encountering the following error:
undefined local variable or method `shipment_options' for #<# <Class:0x007f92941be8f0>:0x007f929ca78ad8>
This error persists even when I use something like locals: { var: @var }
. Below is the code snippet from my view:
<body>
<p>
This is 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>
The route that handles the AJAX request
#AJAX
post '/service_select' => 'dashboards#get_shipment'
The get_shipment
method in the controller
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.js { render json: @shipment_options, action: "new" }
end
And here's the code in the partial I intend to render
<%= 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 %>
Please advise on how to resolve this error. Thank you.