2017-02-20 72 views
0

我怎麼能實現使用強參數如何在軌寫強參數

def create 
     #@user = User.find(params[:user_id]) 

     @listing = Listing.find(params[:listing_id]) 

     if current_user != @listing.user 
         @reservation=Reservation.new(user_id:current_user.id,listing_id:params[:reservation][:listing_id],price:params[:reservation][:price], 
            total:params[:reservation][:total],start_date:params[:reservation][:sdate],end_date:params[:reservation][:edate], 
            driver_name:params[:reservation][:driver_name],no_of_passengers:params[:reservation][:no_of_passengers],days:params[:reservation][:days],reservation_status:false,reservation_state: 'PENDING') 
    else 
     @reservation=Reservation.new(user_id:current_user.id,listing_id:params[:reservation][:listing_id],price:params[:reservation][:price], 
            total:params[:reservation][:total],start_date:params[:reservation][:sdate],end_date:params[:reservation][:edate], 
            driver_name:params[:reservation][:driver_name],no_of_passengers:params[:reservation][:no_of_passengers],days:params[:reservation][:days],reservation_status:false,reservation_state: 'BLOCKED') 
    end 
    @reservation.save 
    end 

我把所有的屬性從哪裏來_form.html.erb接受USER_ID,reservation_status和reservation_state.I可以允許下面創建行動一些屬性爲:

def reservation_params 
    params.require(:reservation).permit(:start_date, :end_date, :price, :listing_id,:total,:driver_name,:no_of_passengers,:days) 

我怎麼能允許所有屬性,包括USER_ID,reservation_status併爲用戶完成預訂reservation_state

在此先感謝!

回答

2

我會像這樣開始:

def reservation_params 
    parameters = params.require(:reservation).permit(
    :listing_id, :sdate, :edate, :driver_name, :no_of_passengers, :days 
) 

    parameters.merge!(user_id: current_user.id, reservation_status: false) 

    if current_user != listing.user 
    parameters.merge!(reservation_state: 'PENDING') 
    else 
    parameters.merge!(reservation_state: 'BLOCKED') 
    end 
end 

def listing 
    @listing ||= Listing.find(params[:listing_id]) 
end 
+0

謝謝@ spickermann.This已經幫了我很多。 – suresh