1

我有一个应用程序,允许用户创建负载并对它们进行投标。

我想要一种方法来完成应用程序并保留投标,然后将处理信用卡,但我在设置保留模型时遇到问题。这是设置:

模型及其关联:

class Reservation < ActiveRecord::Base
  belongs_to :load
  belongs_to :bid

  validates :load_id, presence: true
  validates :bid_id, presence: true
end

class Load < ActiveRecord::Base
  has_many :bids, :dependent => :delete_all
  has_one :reservation
end

class Bid < ActiveRecord::Base
  belongs_to :load
  has_one :reservation
end

预留迁移仅包括对这两个表的引用。在我的预订控制器中,我有以下代码:

class ReservationsController < ApplicationController

  before_filter :find_load
  before_filter :find_bid 

  def new
    @reservation = @load.build_reservation(params[:reservation])
  end

  def create
    @reservation = @load.build_reservation(params[:reservation].merge!(:bid_id => params[:bid_id])) 
    if @reservation.save
      flash[:notice] = "Reservation has been created successfully"
      redirect_to [@load, @bid]
    else
      render :new
    end
  end

  def find_load
    @load = Load.find(params[:load_id])
  end

  def find_bid
    @bid = Bid.find(params[:bid_id])
  end
end

在我的配置路由文件中,我有以下内容:

resources :loads do 
  resources :bids do 
    resources :reservations
  end
end

预留模型的迁移如下所示:

def change
  create_table :reservations do |t|
    t.references :load
    t.references :bid
    t.timestamps
  end
end

查看代码:

<h4>Reserve this bid: </h4>
  <dl>
    <dt>Carrier</dt>
    <dd><%= @bid.user.email %></dd>
    <dt>Bid Amount:</dt>
    <dd><%= @bid.bid_price %></dd>
 </dl>

<%= form_for [@load, @bid, @reservation], :html => {:class => 'payment_form'} do |f| %>
  <%= f.error_messages %>
<fieldset>
  <div class="field">
    <%= label_tag :card_number, "Credit Card Number" %>
    <%= text_field_tag :card_number, nil, name: nil %>
  </div>
  <div class="field">
    <%= label_tag :card_code, "Security Code on Back of Card (CVV)" %>
    <%= text_field_tag :card_code, nil, name: nil %>
  </div>
  <div class="field">
    <%= label_tag :card_month, "Card Expiration" %>
    <%= select_month nil, { add_month_numbers: true }, { name: nil, id: "card_month" } %>
    <%= select_year nil, { start_year: Date.today.year, end_year: Date.today.year+15 },
  { name: nil, id: "card_year" } %>
 </div>
</fieldset>

当我提交表单时,我收到以下验证错误:“投标不能为空”。看起来表单提交的投标是nil,我不确定它为什么这样做。我不相信第一行代码在我的控制器创建操作中是正确的,我已经尝试了所有我能想到的排列,但我无法让它工作。

4

1 回答 1

1

由于您的表单不包含您要保存的任何数据,您可以简单地执行以下操作:

@reservation = @load.build_reservation(:bid_id => @bid.id)

如果您添加将来要保存的预订字段,params[:reservation]则不会nil,您将能够:

@reservation = @load.build_reservation(params[:reservation].merge(:bid_id => @bid.id))

另一种方法是在包含 的表单中添加一个隐藏字段bid_id,但由于您已经在 URL 中拥有它,这可能不是最好的方法。

于 2012-05-18T00:23:22.250 回答