Ruby on rails 在rails中使用简单的表单Submit调用模型方法
我的应用程序上有一个页面,用户可以在其中选择配送选项。我需要将他们的选择添加到数据库中的Ruby on rails 在rails中使用简单的表单Submit调用模型方法,ruby-on-rails,Ruby On Rails,我的应用程序上有一个页面,用户可以在其中选择配送选项。我需要将他们的选择添加到数据库中的order.total。在order.rb模型中,我有以下自定义方法: def update_order_from_shipping_page(shipping) new_total = self.total + self.shipping self.update_attributes(total: new_total) end 在我看来,以下形式: %= simple_form_for @or
order.total
。在order.rb
模型中,我有以下自定义方法:
def update_order_from_shipping_page(shipping)
new_total = self.total + self.shipping
self.update_attributes(total: new_total)
end
在我看来,以下形式:
%= simple_form_for @order, url: charges_update_order_path(:shipping), method: :post do |f| %>
<div class="row">
<div class="form-inputs text-left">
<div class="form-group col-sm-6">
<%= f.collection_radio_buttons :shipping, shipping_choices, :first, :last, item_wrapper_class: :block_radio_button_collection %>
</div>
</div> <!-- form inputs -->
</div> <!-- choices row -->
<div class="row">
<%= f.button :submit, "Calculate Shipping" %>
</div>
<% end %>
我的控制器中有这个:
def update_order
@order = current_order
if @order.update_order_from_shipping_page(shipping)
redirect_to new_charge_path and return
else
redirect_to :back
flash[:notice] = "Something is amuck."
end
end
单选按钮填充正确,不显示控制台或服务器错误,但费用#新建页面上显示的总数不反映模型方法可能触发的更新。有人知道我哪里出错了吗?您的方法接收到一个参数(shipping
),但没有使用它:
def update_order_from_shipping_page(shipping)
new_total = self.total + self.shipping
self.update_attributes(total: new_total)
end
new\u total
正在将self.shipping
添加到self.total
,而不是添加shipping
。因此,除非self.shipping
已经包含任何数据,否则它不会添加任何内容
因此,当您使用以下命令调用该方法时:
@order.update_order_from_shipping_page(shipping)
它没有考虑装运
,也没有更新总计
要解决此问题,请更改“发货”页面中的“更新订单”方法,使其添加“发货”而不是“自发货”。发货
:
def update_order_from_shipping_page(shipping)
new_total = self.total + shipping
self.update_attributes(total: new_total)
end
更新
为避免数组无法强制转换为bigdecim
,您需要从选项数组
中获取正确的值,并将其转换为整数/浮点
。要完成此更新,请更新控制器的update\u order
方法:
def update_order
@order = current_order
shipping = params[:order][:shipping].gsub(/[$,]/,"").to_f # new line added
if @order.update_order_from_shipping_page(shipping)
redirect_to new_charge_path and return
else
redirect_to :back
flash[:notice] = "Something is amuck."
end
end
gsub(/[$,]/,“”)代码>用于删除货币字符($
和,
)
to_f
将字符串
转换为浮点
创建一个操作并提交给它。@MahmoudSayed,谢谢你的参考!我对OP进行了大量更新,但仍然没有看到model方法生效。非常好的捕获!不幸的是,现在我得到的数组不能强制转换为BigDecimal
,因为我在视图中传递:shipping
,它提供了f我的配送选项。我如何让它传递用户在表单上选择的值?@Liz您如何设置if@order.update\u order\u from\u shipping\u页面(配送)中shipping
的值
?完整的表单在OP上,但它当前是
…我知道这不对,但我不知道如何获取表单中选择的值…@Liz我是说在您的控制器中,从表单发送的值可以从参数
散列中检索,在这种情况下应该使用类似参数[:order]的东西[:shipping]
@Liz哪一行将数组强制为BigDecimal
错误?
def update_order
@order = current_order
shipping = params[:order][:shipping].gsub(/[$,]/,"").to_f # new line added
if @order.update_order_from_shipping_page(shipping)
redirect_to new_charge_path and return
else
redirect_to :back
flash[:notice] = "Something is amuck."
end
end