我有一个应用程序,允许用户创建负载并对其进行出价。
我想要一种方法来浏览申请并预订出价然后处理信用卡,但我在设置预订模式时遇到问题。这是设置:
带有关联的模型:
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
,我不确定为什么会这样做。我不相信第一行代码在我的控制器的创建操作中是正确的,并且我已经尝试了所有我能想到的排列并且我无法使其工作。
答案 0 :(得分: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中使用该字段,因此这可能不是最好的方法。