2016-11-29 1 views
0

Я надеюсь, что кто-то может помочь. Я использую драгоценный камень Devise для регистрации и подписания пользователей. У меня есть контроллер профиля. Когда существующий пользователь входит в систему, я хочу, чтобы они были перенаправлены на страницу show.html.erb Profile, чтобы просмотреть их профиль. Я бы ожидать, что это будет сделано в рамках контроллера Sessions, но не похоже, чтобы сделать что-нибудьНевозможно перенаправить Devise sign page, чтобы показать профиль

Код Сессии контроллера:

class Registrations::SessionsController < Devise::SessionsController 
# before_action :configure_sign_in_params, only: [:create] 

    protected 
    def after_sign_in_path_for(resource) 
     profile_path(resource) 
    end 

Однако, когда пользователь регистрируется, редирект успешно работает под зарегистрирования контроллер ниже:

class RegistrationsController < Devise::RegistrationsController 
# before_action :configure_sign_up_params, only: [:create] 
# before_action :configure_account_update_params, only: [:update] 

    protected 
    def after_sign_up_path_for(resource) 
     new_profile_path(resource) 
    end. 

Я также хочу, чтобы иметь ссылку на профиль пользователя страницы, когда они вошли в систему, но когда я делаю это подбрасывает следующее сообщение об ошибке

application.html.erb код ссылки ниже (я попробовал несколько различных переменных вместо «@profile», но без успеха)

<li><%= link_to 'Show Profile', profile_path(@profile), :class => 'navbar-link' %></li> 

Ошибка я получаю это:

ActionController::UrlGenerationError in Profiles#index 

No route matches {:action=>"show", :controller=>"profiles", :id=>nil} missing required keys: [:id] 

Мои маршруты (которые я не уверен, настроены правильно:

Rails.application.routes.draw do 

    resources :profiles 
    get 'profiles/:id', to: 'profiles#show' 
    get '/profiles/new' => 'profiles#new' 
    get '/profiles/edit' => 'profiles#edit' 
    get '/profiles/index' => 'profiles#index' 

    root to: 'pages#index' 

    devise_for :users, :controllers => { :registrations => "registrations" } 

Наконец, мой профиль контроллер:

class ProfilesController < ApplicationController 
before_action :set_profile, only: [:show, :edit, :update, :destroy] 

    def index 
    @search = Profile.search(params[:q]) 
    @profiles = @search.result(distinct: true) 
    end 

    def show 
    @profile = Profile.find(params[:id]) 
    end 

    def new 
    @profile = Profile.new 
    end 

    def create 
    @profile = Profile.new(profile_params) 

    respond_to do |format| 
    if @profile.save 
     format.html { redirect_to @profile, notice: 'Your Profile was successfully created' } 
     format.json { render :show, status: :created, location: @profile } 
    else 
     format.html { render :new } 
     format.json { render json: @profile.errors, status: :unprocessable_entry } 
    end 
    end 
end 

    def edit 
    @profile = Profile.find(params[:id]) 
    end 

    def update 
    respond_to do |format| 

    if @profile.update(profile_params) 
     format.html { redirect_to @profile, notice: 'Profile was successfully updated.' } 
     format.json { render :show, status: :ok, location: @profile } 
    else 
     format.html { render :edit } 
     format.json { render json: @profile.errors, status: :unprocessable_entity } 
    end 
    end 
end 

    def destroy 
    @profile.destroy 

    respond_to do |format| 
     format.html { redirect_to profile_url, notice: 'Profile was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
end 

    def set_profile 
    @profile = Profile.find(params[:id]) 
    end 

    private 
    def profile_params 
     params[:profile][:user_id] = current_user.id 
     params.require(:profile).permit(:full_name, :contact_number, :location, :makeup_type, :bio, :user_id, :image) 
    end  
end 

Любая помощь очень ценится.

ответ

0

В контроллере приложения вы хотите что-то вроде этого

class ApplicationController < ActionController::Base 
    protect_from_forgery with: :exception 

    def after_sign_in_path_for(user) 
    profile_path(current_user) 
    end 
    #user is the model name for example that you created with devise 

end 
+0

Это перенаправлено прямо в профиль, поэтому я отметил его как правильное относительно его маршрутизации. Должен ли я объявить my after_sign_up_path_for (ресурс) в контроллере приложения также вместо регистраций? Что было бы лучшим способом сделать что-то и почему? – marg08

1

ИТАК есть две проблемы:

  1. Перенаправление после знака ошибки генерации
  2. Url в макете приложения

Перенаправление после знака в

Вам нужно добавьте контроллер в определение маршрутов (например, у вас есть регистрации.

devise_for :users, controllers: { registrations: "registrations", sessions: 'registrations/sessions' } 

ошибка генерации Url в макете приложения

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

Если это так, то вы могли бы, скорее всего, сделать что-то вроде этого:

<%= if current_user %> 
    <li> 
    <%= link_to 'Show Profile', profile_path(current_user.profile), :class => 'navbar-link' %> 
    </li> 
<% end %> 

В противном случае, вы должны установить @profile в некоторых before_action в контроллере приложения или в любом контроллере, который использует макет приложения.

+0

Спасибо очень много. Ссылка выше работала. Так что спасибо тебе. Что касается перенаправления после входа в систему, у меня, казалось, были проблемы, когда я добавил маршрутизацию выше. Я думаю, что это было больше связано с тем, как я прописал свое приложение. Я не уверен. В конце я поместил after_sign_in_path_for в контроллер приложения в соответствии с ответом Гурмуха ниже. Я отметил вас несколькими. Еще раз спасибо. – marg08