我是 RoR 的初学者,在使用我的一些模型时遇到了问题。
基本上我在产品票预订之间有一个habtm关系。通过门票预订产品,反之亦然。
我还有一个供应商,它 has_many :products 和 has_many :reservations。
我想要做的是在用户选择供应商并看到它的产品后,他可以从该供应商那里选择他想要的产品。
在那个 reservations.new 中,我得到了一个表单,但是由于在“提交”操作之后我必须在 2 个模型中插入数据,所以我遇到了问题。
当我创建预订时,应该同时创建预订条目和票条目,票条目将具有reservation_id和product_id作为外键。
我的预订观点:
<%= form_for(@reservation) do |f| %>
Reservation Info
<div id="reservation_top"></div>
<div id="reservation">
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= f.label :surname %><br />
<%= f.text_field :surname %>
(...)
<%= f.hidden_field :supplier_id, :value => @reservation.supplier_id %> #to get the supplier ID
Products:
<%= f.fields_for :tickets do |t| %>
<%= t.select("product_id",options_from_collection_for_select(@products, :id, :name))%>
#I also have another t.select and although this isn't my primary concern, I wanted this t.select option's to change according to what is selected on the previous t.select("product_id"). Something like a postback. How is it done in RoR? I've searched and only found observe_field, but I didn't understand it very much, can you point me in the right direction? thanks
<%end%>
<%= f.label :comments %>
<%= f.text_area :comments %>
<%= f.submit%>
<%end%>
现在我认为问题出在我的控制器上,但我不明白该放什么,我目前有:
def new
@supplier=Supplier.find(params[:supplier_id])
@reservation = Reservation.new(:supplier_id => params[:supplier_id])
@ticket = Ticket.new(:reservation_id => params[@reservation.id])
@products = Supplier.find(params[:supplier_id]).products
@ticket = @reservation.tickets.build
respond_to do |format|
format.html
format.json { render :json => @reservation }
end
end
def create
@reservation = Reservation.new(params[:reservation])
respond_to do |format|
if @reservation.save
@reservation.tickets << @ticket
format.html { redirect_to @reservation, :notice => 'Reservation Successful' }
else
format.html { render :action => "new" }
format.json { render :json => @reservation.errors, :status => :unprocessable_entity }
end
end
我现在得到一个
Called id for nil, which would mistakenly be 4
是因为它正在尝试创建票证并且没有reservation_id吗?
我以前从未处理过 habtm 关联。有小费吗?
提前致谢, 问候