私は RoR の初心者で、一部のモデルの操作で問題が発生しています。
基本的には商品・チケット・予約の関係を持っています。チケットを介して製品を予約し、その逆も同様です。
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 関連付けを処理したことがありません。任意のヒント?
よろしくお願いします。