Production Rails 3 Маршруты не работают так же, как Разработка - PullRequest
0 голосов
/ 01 апреля 2012

В настоящее время я пытаюсь запустить приложение Ruby (1.8.7) на Rails (3.0.9) в производственной среде. Однако при переходе в производственную среду у меня возникают серьезные проблемы с маршрутами. Например, в моем коде я ссылался на

user_path()

Но в производстве мне пришлось изменить это на

users_path()

Кажется, это работает, кроме случаев, когда оно используется в

users_path(user)

, который производит URL

http://whatwillworkforme.com/users?format=myuser

Принимая во внимание, что развитие будет производить:

http://whatwillworkforme.com/users/myuser

Мои маршруты показаны ниже. Я использую код проекта Smartr (https://github.com/dkd/smartr), поэтому я не очень знаком с маршрутами Rails 3 или с тем, почему были приняты конкретные решения.

WhatWillWorkForMeCom::Application.routes.draw do

  devise_for :users, :controllers => { :registrations => "registrations",
                                   :passwords      => "passwords",
                                   :sessions      => "sessions" }
  namespace :admin do
    resources :comments
    resources :treatments
    resources :conditions
    resources :users
  end

  match "/conditions/page/:page", :to => "conditions#index"
  match "/conditions/hot(/:page)", :to => "conditions#hot"
  match "/conditions/active(/:page)", :to => "conditions#active"
  match "/conditions/untreated(/:page)", :to => "conditions#untreated"
  match "/conditions/tagged/:tag(/:page)", :to => "condition#index"

  match "sitemap/" => "sitemap#index"

  match 'contact_us' => 'site#contact_us_new', :as => 'contact_us', :via => :get
  match 'contact_us' => 'site#contact_us_create', :as => 'contact_us', :via => :post

  resources :conditions, :except => [:show, :edit] do

    member do
      put :update_for_toggle_acceptance
      put :update_for_toggle_decline
    end

    collection do
      get :hot
      get :active
      get :untreated
      get :search
    end
  end

  match "/conditions/:id(/:friendly_id)", :to => "conditions#show", :as => :condition
  match "/conditions/:id/:friendly_id/edit", :to => "conditions#edit"
  match "/site/terms_and_conditions", :to => "site#terms_and_conditions"

  scope "/conditions/:condition_id/:friendly_id/" do
    get "treatment/:id/edit", :to => "treatments#edit", :as => :edit_condition_treatment
    put "treatment/:id", :to => "treatments#update", :as => :condition_treatment
    post "treatments", :to => "treatments#create", :as => :condition_treatments
  end

  match "/admin", :to => "admin#index"

  resources :comments
  resources :tags, :only => [:index]
  resources :votes, :only => [:create]

  resources :users, :except => [:destroy] do

    collection do
      get :who_is_online
      get :search
    end

    member do
      get :reputation
    end

    resources :bookmarks, :only => [:index]

  end

  resources :bookmarks, :only => [:toggle] do
    member do
      post :toggle
      get :toggle
    end
  end

  match "errors/routing", :to => "errors#routing"

  namespace :api do
    namespace :v1 do
      resources :conditions, :only => [:index]
      resources :users, :only => [:index]
    end
  end

  root :to => 'site#index'
  match '*a', :to => 'errors#routing'
end

Рейк-рейты (по запросу) -

        new_user_session GET    /users/sign_in(.:format)         {:action=>"new", :controller=>"sessions"}
            user_session POST   /users/sign_in(.:format)         {:action=>"create", :controller=>"sessions"}
    destroy_user_session GET    /users/sign_out(.:format)        {:action=>"destroy", :controller=>"sessions"}
           user_password POST   /users/password(.:format)        {:action=>"create", :controller=>"passwords"}
       new_user_password GET    /users/password/new(.:format)    {:action=>"new", :controller=>"passwords"}
      edit_user_password GET    /users/password/edit(.:format)   {:action=>"edit", :controller=>"passwords"}
                         PUT    /users/password(.:format)        {:action=>"update", :controller=>"passwords"}
cancel_user_registration GET    /users/cancel(.:format)          {:action=>"cancel", :controller=>"registrations"}
       user_registration POST   /users(.:format)                 {:action=>"create", :controller=>"registrations"}
   new_user_registration GET    /users/sign_up(.:format)         {:action=>"new", :controller=>"registrations"}
  edit_user_registration GET    /users/edit(.:format)            {:action=>"edit", :controller=>"registrations"}
                         PUT    /users(.:format)                 {:action=>"update", :controller=>"registrations"}
                         DELETE /users(.:format)                 {:action=>"destroy", :controller=>"registrations"}
       user_confirmation POST   /users/confirmation(.:format)    {:action=>"create", :controller=>"devise/confirmations"}
   new_user_confirmation GET    /users/confirmation/new(.:format){:action=>"new", :controller=>"devise/confirmations"}
                         GET    /users/confirmation(.:format)    {:action=>"show", :controller=>"devise/confirmations"}
who_is_online_users GET    /users/who_is_online(.:format)      {:action=>"who_is_online", :controller=>"users"}
       search_users GET    /users/search(.:format)             {:action=>"search", :controller=>"users"}
    reputation_user GET    /users/:id/reputation(.:format)     {:action=>"reputation", :controller=>"users"}
     user_bookmarks GET    /users/:user_id/bookmarks(.:format) {:action=>"index", :controller=>"bookmarks"}
              users GET    /users(.:format)                    {:action=>"index", :controller=>"users"}
                    POST   /users(.:format)                    {:action=>"create", :controller=>"users"}
           new_user GET    /users/new(.:format)                {:action=>"new", :controller=>"users"}
          edit_user GET    /users/:id/edit(.:format)           {:action=>"edit", :controller=>"users"}
               user GET    /users/:id(.:format)                {:action=>"show", :controller=>"users"}
                    PUT    /users/:id(.:format)                {:action=>"update", :controller=>"users"}

1 Ответ

0 голосов
/ 02 апреля 2012

Я не уверен, почему поведение при разработке и производстве отличается, но http://whatwillworkforme.com/users?format=myuser на самом деле ожидаемое поведение на users_path(myuser).Вы можете проверить это, запустив rake routes.Вы должны получить что-то вроде этого:

users GET    /users(.:format)        users#index
 user GET    /users/:id(.:format)    users#show

Все, что имеет начальную двоеточие в маршрутах, будет аргументом, который вы можете передать url_for, или всем, что его использует, например.link_to.

Вы должны использовать user_path(user) для получения маршрута конкретного пользователя (Rails преобразует экземпляр ActiveRecord в id перед передачей его в маршрут).

И наоборот, вы должны использовать users_path без аргументов, так как вы ссылаетесь на всю коллекцию, используя множественный маршрут.Любой аргумент будет пытаться задать формат для вашего URL (например, 'xml' должен добавить конечный .xml к URL).

В вашем конкретном случае также следите за дублированным маршрутом: POST вызовы на /users будут перехвачены Devise и не достигнут вашего контроллера create action.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...