狂欢3.1:在交货步骤中将选择标签添加到装运表单

时间:2016-10-02 13:49:09

标签: ruby-on-rails spree

我正在尝试在结帐时以装运形式为城市添加一个选择标签。

#views/spree/checkout/_delivery.html.erb

<%= form.fields_for :shipments do |ship_form| %>
  <% ship_form.object.shipping_rates.each do |rate| %>
    <tr class="stock-item">
        <td class="shipment-button"><%= ship_form.radio_button :selected_shipping_rate_id, rate.id %></td>
        <td class="rate-name"><%= rate.name %></td>
        <td class="item-qty"></td>
        <td class="rate-cost"><%= rate.display_cost %></td>
    </tr>
    <% if rate.shipping_method_id == 4 %>
        <tr id="city" style="display: none">
            <td></td>
            <td>
            <%= ship_form.select :selected_city_id, options_from_collection_for_select(@cities, "id", "name"), { :include_blank => true }, { :class => "select-city" } %>
            </td>
            <td></td>
            <td></td>
        </tr>
    <% end %>
<% end %>

模型发货:

#models/spree/shipment.rb

def selected_shipping_rate
  shipping_rates.where(selected: true).first
end

def selected_shipping_rate_id
  selected_shipping_rate.try(:id)
end

def selected_city_id
  selected_shipping_rate.try(:selected_city_id)
end

结帐控制器:

#controller/spree/checkout_controller.rb

def update
  if @order.update_from_params(params, permitted_checkout_attributes, request.headers.env)
    @order.temporary_address = !params[:save_user_address]
    unless @order.next
      flash[:error] = @order.errors.full_messages.join("\n")
      redirect_to(checkout_state_path(@order.state)) && return
    end
    if @order.completed?
      @current_order = nil
      flash.notice = Spree.t(:order_processed_successfully)      
      flash['order_completed'] = true
      redirect_to completion_route
    else
      redirect_to checkout_state_path(@order.state)
    end
  else
    render :edit
  end
end

选择框用于选择可提供送货方式的城市。

我在表spree_shipments中添加了新列 我还在selected_city_id中添加了方法models/spree/shippment.rb,并在初始化程序中允许了新参数。

但是当我试图获得@order.shipments.order("created_at").last.selected_city_id时 我得到NoMethodError: undefined method selected_city_id

提交后的Prams看起来像这样:

"order"=>{
   "shipments_attributes"=>{
   "0"=>{"selected_city_id"=>"10", 
   "selected_shipping_rate_id"=>"10",
   "id"=>"4"}
   }
}

我想我在这里错过了一些东西...... 请有人帮助我,如何在db中保存selected_city_id?它应该保存在不同的表中(spree_shipping_rates)吗?

由于

1 个答案:

答案 0 :(得分:0)

<强>解决方案:

我在Shipment模型中添加了另一个方法

#models/spree/shipment.rb

def selected_shipping_rate
  shipping_rates.where(selected: true).first
end

def selected_shipping_rate_id
  selected_shipping_rate.try(:id)
end

def selected_city_id
  selected_shipping_rate.try(:selected_city_id)
end

def selected_city_id=(id)
  selected_shipping_rate.update(selected_city_id: id)
end