【问题标题】:is it a clean way to create shipping options in rails?在 Rails 中创建运输选项是一种干净的方法吗?
【发布时间】:2023-03-06 07:05:01
【问题描述】:

我对 ROR 不是很有经验,它是一种在 rails 应用程序中创建运输选项的简洁方法吗?

刚刚在我的 orders_form 中添加了这段代码:

<% if @order.subtotal >= 30 %>
  (free shipping)
  <%= f.radio_button(:shipping, "0.00", :checked => "checked", class: "hidden_field") %><br/>
<% else %>
  <p><strong>Shipping options :</strong></p>
  <%= f.label 'economy' %>
  <%= f.radio_button(:shipping, "3.00", :checked => "checked") %><br/>
  <%= f.label 'fast' %>
  <%= f.radio_button(:shipping, "5.00") %>
<% end %>

对我来说似乎太简单了。

【问题讨论】:

    标签: ruby-on-rails ruby form-helpers


    【解决方案1】:

    一切都很好,但最好将所有这些逻辑保留在模型中,而不是视图中。像这样的:

    # order.rb
    class Order < ActiveRecord::Base
      FREE_SHIPPING_THRESHOLD = 30.0
      ECONOMY_SHIPPING_PRICE = 3.0
      FAST_SHIPPING_PRICE = 5.0
    
      ...
    
      def eligible_for_free_shipping?
        subtotal >= FREE_SHIPPING_THRESHOLD
      end
    end
    

    然后&lt;% if @order.subtotal &gt;= 30 %&gt; 变为&lt;% if @order.eligible_for_free_shipping? %&gt;,而不是在您使用Order::ECONOMY_SHIPPING_PRICEOrder::FAST_SHIPPING_PRICE 的视图中硬编码运费。

    通过这种方法,您可以将所有订单运输设置集中在一个地方,因此当您想要更改某些内容时,无需查看多对多文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 2011-09-07
      • 2023-03-03
      • 2010-09-12
      • 1970-01-01
      相关资源
      最近更新 更多