2015-12-14 5 views
1

Я пытаюсь вложить ресурсы таким образом, чтобы избежать вложенности ресурса 3 в глубину.ActionController :: Ошибка маршрутизации (вложенные ресурсы - Rails 4 Ruby 2)

мой первоначальный план был сделать что-то вроде: (только так вы можете увидеть мой мыслительный процесс)

resources :properties do 
    resources :stalls do 
     resources :bookings 
    end 
    end 
end 

То, что я в конечном итоге делает это:

## Nested Relationship for Proerty/Stall ## 
    resources :properties do 
    resources :stalls, except: [:index], controller: 'properties/stalls' 
    end 
    ## END Nested Relationship for Property/Stall ## 

    ## Nested Relationship for Stall/Bookiing ## 
    resources :stalls do 
    resources :bookings, except: [:index], controller: 'stalls/bookings' 
    end 
    ## END Nested Relationship for Stall/Bookiing ## 

Каждая вещь работает до такой степени, что я отправляю форму бронирования. И даже при этом доза фиксирует бронирование и создает запись, но dosnt перенаправляет обратно в киоски/1.

ошибка сервера:

Started POST "/stalls/1/bookings" for ::1 at 2015-12-13 23:12:39 -0700 
    ActiveRecord::SchemaMigration Load (0.3ms) SELECT "schema_migrations".* FROM "schema_migrations" 
Processing by Stalls::BookingsController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"xsGxr2PLf7vHuXL6xgjBHyTl2Ub8mD07S7iJXM7vNodjH32DXgdUELFk6pJSUxZhkp+sZS31g4E4kY9AVnDyoQ==", "booking"=>{"stall_id"=>"", "visitor_id"=>"", "arrival_date(1i)"=>"2015", "arrival_date(2i)"=>"12", "arrival_date(3i)"=>"14", "arrival_time(1i)"=>"2015", "arrival_time(2i)"=>"12", "arrival_time(3i)"=>"14", "arrival_time(4i)"=>"06", "arrival_time(5i)"=>"08", "departure_date(1i)"=>"2015", "departure_date(2i)"=>"12", "departure_date(3i)"=>"14"}, "commit"=>"Create Booking", "stall_id"=>"1"} 
    Stall Load (0.4ms) SELECT "stalls".* FROM "stalls" WHERE "stalls"."id" = $1 LIMIT 1 [["id", 1]] 
    (0.1ms) BEGIN 
    SQL (0.5ms) INSERT INTO "bookings" ("arrival_date", "arrival_time", "departure_date", "stall_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["arrival_date", "2015-12-14"], ["arrival_time", "2015-12-14 06:08:00.000000"], ["departure_date", "2015-12-14"], ["stall_id", 1], ["created_at", "2015-12-14 06:12:40.035416"], ["updated_at", "2015-12-14 06:12:40.035416"]] 
    (6.0ms) COMMIT 
Redirected to http://localhost:3000/stalls/1 
Completed 302 Found in 53ms (ActiveRecord: 10.4ms) 


Started GET "/stalls/1" for ::1 at 2015-12-13 23:12:40 -0700 

ActionController::RoutingError - uninitialized constant StallsController: 
    actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:65:in `rescue in controller' 
    actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:60:in `controller' 
    actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:41:in `serve' 
    actionpack (4.2.3) lib/action_dispatch/journey/router.rb:43:in `block in serve' 
    actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `serve' 
    actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:821:in `call' 
    warden (1.2.4) lib/warden/manager.rb:35:in `block in call' 
    warden (1.2.4) lib/warden/manager.rb:34:in `call' 
    rack (1.6.4) lib/rack/etag.rb:24:in `call' 
    rack (1.6.4) lib/rack/conditionalget.rb:25:in `call' 
    rack (1.6.4) lib/rack/head.rb:13:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call' 
    rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context' 
    rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call' 
    activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call' 
    activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' 
    activerecord (4.2.3) lib/active_record/migration.rb:377:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' 
    activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks' 
    actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' 
    better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call' 
    better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call' 
    better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' 
    web-console (2.2.1) lib/web_console/middleware.rb:39:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' 
    railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app' 
    railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call' 
    activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged' 
    activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged' 
    activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged' 
    railties (4.2.3) lib/rails/rack/logger.rb:20:in `call' 
    quiet_assets (1.1.0) lib/quiet_assets.rb:27:in `call_with_quiet_assets' 
    actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call' 
    rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' 
    rack (1.6.4) lib/rack/runtime.rb:18:in `call' 
    activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' 
    rack (1.6.4) lib/rack/lock.rb:17:in `call' 
    actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call' 
    rack (1.6.4) lib/rack/sendfile.rb:113:in `call' 
    railties (4.2.3) lib/rails/engine.rb:518:in `call' 
    railties (4.2.3) lib/rails/application.rb:165:in `call' 
    rack (1.6.4) lib/rack/lock.rb:17:in `call' 
    rack (1.6.4) lib/rack/content_length.rb:15:in `call' 
    rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service' 
    /Users/TaurenLTD1/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service' 
    /Users/TaurenLTD1/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run' 
    /Users/TaurenLTD1/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread' 

Мой Лавки контроллер как таковой:

class Properties::StallsController < ApplicationController 
    before_action :set_stall, only: [:show, :edit, :update, :destroy] 

    # GET /stalls 
    # GET /stalls.json 
    def index 
    @stalls = Stall.all 
    end 

    # GET /stalls/1 
    # GET /stalls/1.json 
    def show 
    @stall = Stall.find(params[:id]) 
    ## Nested Bookings ## 
    @bookings = @stall.bookings 
    end 

    # GET /stalls/new 
    def new 
    @property = Property.find(params[:property_id]) 
    @stall = Stall.new 
    end 

    # GET /stalls/1/edit 
    def edit 
    end 

    # POST /stalls 
    # POST /stalls.json 
    def create 
    @property = Property.find(params[:property_id]) 
    @stall = Stall.new(stall_params) 
    @stall.property = @property 

    respond_to do |format| 
     if @stall.save 
     format.html { redirect_to @property, notice: 'Stall was successfully created.' } 
     format.json { render :show, status: :created, location: @property } 
     else 
     format.html { render :new } 
     format.json { render json: @property.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /stalls/1 
    # PATCH/PUT /stalls/1.json 
    def update 
    respond_to do |format| 
     if @stall.update(stall_params) 
     format.html { redirect_to @stall, notice: 'Stall was successfully updated.' } 
     format.json { render :show, status: :ok, location: @stall } 
     else 
     format.html { render :edit } 
     format.json { render json: @stall.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /stalls/1 
    # DELETE /stalls/1.json 
    def destroy 
    @stall.destroy 
    respond_to do |format| 
     format.html { redirect_to stalls_url, notice: 'Stall was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_stall 
     @stall = Stall.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def stall_params 
     params.require(:stall).permit(:property_id, :stall_type, :location, :status) 
    end 
end 

Я думаю, что моя проблема в том, что контроллер был переработан, чтобы иметь отношения с свойства, я попытался создать новый контроллер киосков, но это тоже не сработало.

Просто для справки мой контроллер заказов является:

class Stalls::BookingsController < ApplicationController 
    before_action :set_booking, only: [:show, :edit, :update, :destroy] 

    # GET /bookings 
    # GET /bookings.json 
    def index 
    @bookings = Booking.all 
    end 

    # GET /bookings/1 
    # GET /bookings/1.json 
    def show 
    end 

    # GET /bookings/new 
    def new 
    @stall = Stall.find(params[:stall_id]) 
    @booking = Booking.new 
    end 

    # GET /bookings/1/edit 
    def edit 
    end 

    # POST /bookings 
    # POST /bookings.json 
    def create 
    @stall = Stall.find(params[:stall_id]) 
    @booking = Booking.new(booking_params) 
    @booking.stall = @stall 
    respond_to do |format| 
     if @booking.save 
     format.html { redirect_to @stall, notice: 'Booking was successfully created.' } 
     format.json { render :show, status: :created, location: @stall } 
     else 
     format.html { render :new } 
     format.json { render json: @stall.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /bookings/1 
    # PATCH/PUT /bookings/1.json 
    def update 
    respond_to do |format| 
     if @booking.update(booking_params) 
     format.html { redirect_to @booking, notice: 'Booking was successfully updated.' } 
     format.json { render :show, status: :ok, location: @booking } 
     else 
     format.html { render :edit } 
     format.json { render json: @booking.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /bookings/1 
    # DELETE /bookings/1.json 
    def destroy 
    @booking.destroy 
    respond_to do |format| 
     format.html { redirect_to bookings_url, notice: 'Booking was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_booking 
     @booking = Booking.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def booking_params 
     params.require(:booking).permit(:visitor_id, :stall_id, :arrival_date, :arrival_time, :departure_date) 
    end 
end 

File Tree Изображение: enter image description here

Ошибка Ошибка экрана (better_errors камень, используемый) enter image description here

Любая помощь здесь было бы здорово, я исчерпал все свои ресурсы, прочитал рубиновый гид, просто не знаю, где я здесь ошибся.

Пожалуйста, дайте мне знать, если вам нужна дополнительная информация.

Заранее спасибо.

EDIT # 1:

дисплеи Предлагаемые изменения: enter image description here

Отображает новые Сообщение об ошибке:

enter image description here

ответ

1

Вы используете:

## Nested Relationship for Stall/Bookiing ## 
    resources :stalls do 
    resources :bookings, except: [:index], controller: 'stalls/bookings' 
    end 

, а затем, когда вы делаете:

redirect_to @stall 

Он ищет контроллер под названием StallsController, но у вас нет такого контроллера, у вас есть Properties::StallsController.

Так попробуйте изменить свой маршрут, чтобы выглядеть следующим образом:

resources :stalls, controller: 'properties/stalls' do 
    resources :bookings, except: [:index], controller: 'stalls/bookings' 
    end 
+0

, который просто сделал это! вау что-то такое маленькое .. спасибо за помощь! –

+0

это просто научило меня чему-то новому, очень ценю, что ive застрял на этом в течение нескольких дней .. –

+0

Рад, что я мог бы помочь :) –

1

Вы, кажется, нужно использовать пространство имен на ваших маршрутах

например:

namespace :admin do 
    resources :articles, :comments 
end 

check this in the guide

+0

Ok плохо дать ему попробовать, так что если у меня есть несколько пространств имен бы я просто скопировать из контроллера в другие пространства имен? и тогда я бы изменил класс контроллера на admin :: properties? –

+0

игнорировать вопрос рефакторинга, который был близок при чтении документации по маршрутизации. –

+0

Я получаю тот же eror, используя пространства имен? –

Смежные вопросы