Приложение Rails сообщает, что не может найти маршрут пользователя, должно работать

У меня возникла проблема со входом в мое существующее приложение с пользовательской авторизацией. При входе получаю ошибку

No route matches {:action=>"show", :controller=>"users", :locale=>#<User id: 4, first_name: "asd", last_name: "asd", email: "[email protected]", password_digest: "$2a$10$FDkc/CkjbwS455r/s.OF9uXUzuRmzz3zsYEejij.0KCT...", access_level: 3, last_login

Вот мой файл маршрутов

Islasdelsol::Application.routes.draw do
  scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
    root :to => 'sites#index'
    get "logout" => "sessions#destroy", :as => "logout"
    get "login" => "sessions#new", as: "login"

    resources :sites, except: [:new, :show, :destroy, :create] do
      collection do
      get :about_us
      get :contact_us
      get :news
      get :reservations
      get :sell
      get :tour
    end
  end

resources :users do
  collection do
    get :monthly_letter
    get :admin
    get :regime
    get :general_assembly
    get :monthly_record
    get :newowner
    get :financial_report
    get :email_owners
  end
end

resources :email_owners do
  collection do
    get :email
    get :islas
    post :email
    post :islas
  end
end

resources :regimes do
  collection do
    get :spanish
    get :english
  end
end

resources :general_assemblies do
  collection do
    get :spanish
    get :english
  end
end
resources :sessions
resources :monthly_letters
resources :monthly_records


resources :financial_reports do
  collection do
    get :monthly
    get :yearly
  end
  end
  match "*path", to: "sites#not_found" # handles /en/fake/path/whatever
end
root to: redirect("/#{I18n.default_locale}") # handles /
match '*path', to: redirect("/#{I18n.default_locale}/%{path}")
end

Вот мой контроллер сеансов и форма, откуда исходит вызов

class SessionsController < ApplicationController
  def create
  user = User.find_by_email(params[:email])
  if user && user.authenticate(params[:password])
    session[:user_id] = user.id
    redirect_to user, :notice => "Logged in!"
  else
    flash.now.alert = "Invalid email or password"
    render "new"
  end
end

Форма

<%= form_tag sessions_path do %>
<table>
    <tr>
        <td><label for="email">Email</label></td>
    </tr>
    <tr>
        <td><%= text_field_tag :email, params[:email] %> </td>
    </tr>
    <tr>
        <td>Password</td>
    </tr>
    <tr>
        <td><label for="password"><%= password_field_tag :password %>   </label></td>
    </tr>
    <tr> 
        <td><%= submit_tag "Log in" %> </td>
    </tr>
</table>
<% end %>

def destroy
  session[:user_id] = nil
  redirect_to root_url, :notice => "Logged out!"
end

end

И мои рейк-роуты controller=users

monthly_letter_users GET    /:locale/users/monthly_letter(.:format)   {:locale=>/en|es/, :action=>"monthly_letter", :controller=>"users"}
admin_users GET    /:locale/users/admin(.:format)            {:locale=>/en|es/, :action=>"admin", :controller=>"users"}
regime_users GET    /:locale/users/regime(.:format)           {:locale=>/en|es/, :action=>"regime", :controller=>"users"}
general_assembly_users GET    /:locale/users/general_assembly(.:format) {:locale=>/en|es/, :action=>"general_assembly", :controller=>"users"}
monthly_record_users GET    /:locale/users/monthly_record(.:format)   {:locale=>/en|es/, :action=>"monthly_record", :controller=>"users"}
newowner_users GET    /:locale/users/newowner(.:format)         {:locale=>/en|es/, :action=>"newowner", :controller=>"users"}
financial_report_users GET    /:locale/users/financial_report(.:format) {:locale=>/en|es/, :action=>"financial_report", :controller=>"users"}
email_owners_users GET    /:locale/users/email_owners(.:format)     {:locale=>/en|es/, :action=>"email_owners", :controller=>"users"}
users GET    /:locale/users(.:format)                  {:locale=>/en|es/, :action=>"index", :controller=>"users"}
POST   /:locale/users(.:format)                  {:locale=>/en|es/, :action=>"create", :controller=>"users"}
new_user GET    /:locale/users/new(.:format)              {:locale=>/en|es/, :action=>"new", :controller=>"users"}
edit_user GET    /:locale/users/:id/edit(.:format)         {:locale=>/en|es/, :action=>"edit", :controller=>"users"}
user GET    /:locale/users/:id(.:format)              {:locale=>/en|es/, :action=>"show", :controller=>"users"}
PUT    /:locale/users/:id(.:format)              {:locale=>/en|es/, :action=>"update", :controller=>"users"}
DELETE /:locale/users/:id(.:format)              {:locale=>/en|es/, :action=>"destroy", :controller=>"users"}

Итак, может ли кто-нибудь увидеть, где проблема? Кажется, есть маршрут к странице показа пользователей...

Изменить: Контроллер пользователей

class UsersController < ApplicationController
  helper_method :sort_column, :sort_direction
  def index
    @owners = User.owners.search(params[:search]).order(sort_column + " " +      sort_direction).page(params[:page]).per_page(5)

  end

  def new
    @user = User.new
  end


  def show
    @user = User.find(params[:id])
    @monthly_letters = MonthlyLetter.recent
  end 

   def create
 @user = User.new(params[:user])
    if @user.save
      flash[:notice] = 'User Created!'
      redirect_to @user
    else
      flash[:alert] = "User has not been created."
     render "index"
   end 
  end

  def destroy
    @user = User.find(params[:id])
    @user.destroy
    flash[:notice] = "User has been deleted."
    redirect_to current_user
  end

  def update
    @user = User.find(params[:id])

    if @user.update_attributes(params[:user])
      flash[:notice] = "User has been updated."
      redirect_to @user
    else 
      flash[:alert] = "User has not been updated."
      render :action => "edit"
    end
  end

  def monthly_letter
    @monthly_letter = MonthlyLetter.new
  end 
end

person ruevaughn    schedule 18.04.2012    source источник
comment
Можете ли вы опубликовать свое мнение для пользователя # показать? Я обнаружил, что это обычно происходит, когда у вас есть ‹code›link_to‹/code›, который содержит неверную или отсутствующую информацию в представлении, на которое вы пытаетесь перенаправить.   -  person Paul Simpson    schedule 19.04.2012


Ответы (1)


Проблема в том, что url_for не знает, что делать с параметром :locale.

Вы можете сказать, что происходит в ошибке, потому что она говорит, что параметр :locale является объектом #‹User›. Это должна быть строка, как и другие параметры. Обычно это означает, что ваш link_to/url_for вызывается с неверными или неполными параметрами.

Первым шагом к решению этой проблемы, вероятно, является установка значения по умолчанию для параметра :locale в контроллере вашего приложения. документ i18n руководства по Rails содержит руководство по это, а также более полные решения для просмотра заголовков и параметров HTTP.

person Daniel Evans    schedule 23.04.2012
comment
Спасибо, в итоге я добавил URL-адрес по умолчанию в свой application_controller, например def default_url_options(options = {}) {locale: I18n.locale} end - person ruevaughn; 27.04.2012
comment
Я понимаю, что ты имеешь в виду. Параметр :locale был пользовательским объектом, как он и говорит, и он должен быть строкой либо «en», либо любой другой локали, поэтому я должен был знать, что он передает объект, а не строку. Спасибо Даниэль. - person ruevaughn; 27.04.2012