admincontroller использует неправильный помощник для создания действия - PullRequest
0 голосов
/ 22 марта 2012

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

ActiveRecord::RecordNotFound in AdminsController#show: Couldn't find User with id=4

Трассировка указывает, что она пытается использовать помощника сеансов (для пользователя) вместо соответствующего помощника администраторов.

app/helpers/sessions_helper.rb:20:in `current_user'
app/helpers/sessions_helper.rb:12:in `signed_in?'
app/views/layouts/application.html.erb:13:in  
app_views_layouts_application_html_erb__1013605049_93953830

Я могу правильно войти в систему и администратор создан. Я просто думаю, что проблема связана с redirect_to @admin в моем контроллере администратора, хотя я не уверен.

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

adminsessions_controller.rb

class AdminsessionsController < ApplicationController
  def new
    @title = "Log in"
  end

  def show
    @title = "Admin session"
  end  

  def create
    admin = Admin.authenticate(params[:adminsession][:email],
                               params[:adminsession][:password])
    if admin.nil?
      flash.now[:error] = "Invalid email/password combination."
      @title = "Log in"
      render 'new'
    else
      sign_in admin
      redirect_to admin
    end
  end

  def destroy
    sign_out
    redirect_to root_path                          
  end
end

admins_controller.rb

class AdminsController < ApplicationController

  def index
    @user = User.all
  end

  def show
    @admin = Admin.find(params[:id])
  end

  def new
    @admin = Admin.new
    @title = "New admin"
  end

  def create
     @admin = Admin.new(params[:admin])
    if @admin.save
      sign_in @admin
      flash[:success] = "Welcome admin!"
      redirect_to @admin
    else
      @title = "New admin"
      render 'new'
    end
  end
end

new.html.erb (форма, в которой я создаю нового пользователя)

<div id="signupform_new">
   <%= form_for(@admin) do |f| %>
   <div class="field">
     <%= f.label :username %>
     <%= f.text_field :name, :class => "round"  %>
   </div>
   <div class="field">
     <%= f.label :email %>
     <%= f.text_field :email, :class => "round" %>
    </div>
    <div class="field">
      <%= f.label :password %>
      <%= f.password_field :password, :class => "round"  %>
    </div>
    <div class="field">
       <%= f.label :password_confirmation, "Confirmation" %>
       <%= f.password_field :password_confirmation, :class => "round"  %>
    </div>
    <div class="action">
      <%= button_tag "", :class => "acctSubmit" %>
    </div>
  <% end %>
</div>

sessions_helper.rb

module SessionsHelper

  def sign_in(user)
    session[:user_id] = user.id
    self.current_user = user
  end


  def signed_in?
   !current_user.nil?
  end

  def current_user=(user)
   @current_user = user
  end

  def current_user
   @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def current_user?(user)
   user == current_user
  end

 def authenticate
  deny_access unless signed_in?
 end    

 def sign_out
  session[:user_id] = nil
  self.current_user = nil
end

 def redirect_back_or(default)
  redirect_to(session[:return_to] || default)
  clear_return_to
end

def deny_access
  store_location
  redirect_to login_path, :notice => "Please log in to access this page."
end

private

  def store_location
    session[:return_to] = request.fullpath
  end

  def clear_return_to
    session[:return_to] = nil
  end
end

adminsessions_helper.rb

module AdminsessionsHelper


def sign_in(admin)
  adminsession[:admin_id] = admin.id
  self.current_admin = admin
end


def signed_in?
  !current_admin.nil?
end

def current_admin=(admin)
  @current_admin = admin
end

def current_admin
  @current_admin ||= Admin.find(adminsession[:admin_id]) if adminsession[:admin_id]
end

def current_admin?(admin)
  admin == current_admin
end

def authenticate
  deny_access unless signed_in?
end 

def sign_out
  adminsession[:admin_id] = nil
  self.current_admin = nil
end

def redirect_back_or(default)
  redirect_to(adminsession[:return_to] || default)
  clear_return_to
end

def deny_access
  store_location
 redirect_to login_path, :notice => "Please log in to access this page."
end

private

  def store_location
    adminsession[:return_to] = request.fullpath
  end

  def clear_return_to
    adminsession[:return_to] = nil
  end
end

1 Ответ

2 голосов
/ 22 марта 2012

Все помощники (по умолчанию) смешаны и доступны во всех контроллерах. Похоже, методы, которые вы используете, должны быть защищены или закрыты для членов ваших контроллеров. Вы можете сделать их вспомогательными методами, чтобы они были доступны в ваших представлениях, т.е. helper_method :signed_in?.

Лично мне никогда не нравилось отсутствие пространства имен с помощниками. Мне больше нравится шаблон презентации (см. RailsCasts Pro ].

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