2017-09-27 27 views
1

我的預留數據庫和汽車數據庫之間有多對多的關係,以下內容位於我的預訂控制器中,並被路由到該信息。update_all沒有上傳我的數據庫

def reserveConfirm 

pick_time = params[:pick_y].to_s+"-"+params[:pick_m].to_s+"-"+params[:pick_d].to_s+" "+"#{params[:pick_h]}:00:00" 
return_time = params[:return_y].to_s+"-"+params[:return_m].to_s+"-"+params[:return_d].to_s+" "+"#{params[:return_h]}:00:00" 
#@reservation = Reservation.find(params[:id]) 
@car = Car.where(:id => params[:car_id]).update(:status => 'reserved') 
@reservation = Reservation.new(status:'reserved', 
           pick_up_time: pick_time, 
           return_time: return_time, 
           user_id:current_user.id) 



    if @reservation.save 
    #flash[:success] = @reservation.id 
    flash[:success] = 'shit' 
    redirect_to(:action => 'history',:notice => 'Check out was successfully created.',:id =>current_user.id) 
    else 
    flash[:success] = 'success' 
    format.html { render action: "reserve" } 
    format.json { render json: @reservation.errors.full_messages, status: :unprocessable_entity } 
    end 
end 

事情開始變得混亂從這裏。在我的預訂控制器中,每當我需要params [:id]時,我都沒有收到預留ID。我已創建新的預留並路由到行動儲備。 [:id]似乎是零或一個car_id,因爲我有的鏈接是保留/:id(:格式),而這:id是汽車ID,而不是我的新的預訂ID。我的預訂行動確實Reservation.new

def reserve 
@reservation = Reservation.new 
@car = Car.find(params[:car_id]) 
if @car == nil 
    flash[:danger] = "no car found" 
else 
    flash[:danger] = @car.id 
end 
respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @reservation } 
end 
end 

我在叢林中,一切都在樹林裏糾纏不清。 在保留的行動,我可以找到car_id這是保留/:id字段,這是2在這裏。但在我的reserveConfirm中,我得到了一個零的@car對象,這迫使我使用找到所有帶id的車,儘管只有一個導致id是唯一的。更糟糕的是,在我收到@car後,我想將其狀態更新爲保留狀態,但是當我查看db時,它不會改變。

我的形式,它傳遞的數據是在這裏:

<%= form_for @reservation,:url => { :action => "reserveConfirm" } do |f| %> 

<%=f.label :Date%> 
<%=f.date_select :pick_up_time %> 

<%= f.hidden_field :car_id, :value=> @car.id %> 

<%= f.hidden_field :user_id, :value=> current_user.id %> 

<%= f.submit "Confirm", data: { confirm: 'Are you sure?', class: "btn btn-default" }%> 

希望有人能好心幫助我,非常感激!

回答

2

首先,您應該驗證您是否正確獲取了@car。

我想你可以使用'byebug'。嘗試在reserveConfirm方法開始時寫'byebug'。

def reserveConfirm 
    byebug 
    #your code 
end 

使用byebug,你可以看看你的rails服務器(在終端)和調試你的代碼。嘗試寫'params'來檢查你所接收的所有參數。你可以使用byebug編寫'exit'或'continue'。 (更多信息:Debugging using byebug

如果PARAMS [:car_id]存在,你的代碼應該是這樣的:

@car = Car.find(params[:car_id]) 
@car.status = 'reserved' 
if @car.update 
    #code 
else 
    #code 
end 

檢查,告訴我是怎麼回事。

+0

謝謝你提到漂亮的調試器。事實上,它顯示car_id存在,但當action爲reserveConfirm時,它位於[:reservation] [:car_id]之下,但當它處於action reserve時,它是param [:car_id]。汽車id會被傳遞給我的控制器,而不是保留ID。我預計每一個新的預訂都可能有一個id,例如/localhost/reservation/1..n等,然後是它後面的car_id,它變成/reservation/1..n(reservation_id)/1..n (car_id),但現在,無論何時我創建新的預訂表單,在我提交之前,始終是/ reservation /:car_id。 – user3431800

+0

好的,我明白,你是否在你的路線中使用嵌套資源? –

相關問題