2014-09-19 1 views
1
내가 함께와 고안 레일 4를 사용하고

routes.rb업데이트/

devise_for :users, :path => '', 
    :path_names => {:sign_in => 'login', :sign_out => 'logout', :sign_up => 'register'}, 
    controllers: { registrations: "registrations", omniauth_callbacks: 'omniauth_callbacks' } do 
    get "/login" => "devise/sessions#new" 
    get "/signup" => "devise/registrations#new" 
    get "/logout" => "devise/sessions#destroy" 
    get "/login" => "devise/sessions#new" 
end 


resources :users, :only => [:show, :index], :path => "bloggers" do 
    resources :posts, :path => "articles" 
end 

을 지금이 같은 새 게시물을 만들 때 현재 사용자가 로그인했습니다 (ID가 1이라고 가정합니다). Post -> New 작업의 URL은 ->https://localhost:3000/bloggers/1/articles/new으로 표시되지만 게시물에 대한 새로운 작업은 항상 current_user와 연결되어야하므로 https://localhost:3000/articles/new으로 표시하고 싶습니다.

나는 이것이 가능한 것이라고 상상할 수 있지만, 어떻게해야 할지를 모른다.

또한 user has_many posts입니다.

도와주세요.

답변

1

인증

실제로 매우 간단합니다 :

#config/routes.rb 
# If you have overridden "path_names", you don't need other paths for Devise 
devise_for :users, :path => '', 
    :path_names => {:sign_in => 'login', :sign_out => 'logout', :sign_up => 'register'}, 
    controllers: { registrations: "registrations", omniauth_callbacks: 'omniauth_callbacks' } 

resources :posts, as: "articles", path: "articles" 

#app/controllers/application_controller.rb 
class ApplicationController < ActionController::Base 
    before_action :authenticate_user!, except: :index 

    def index 
     #Stuff here 
    end 

end 

여기 결론은 당신이 인증 영역 (특히 고안에) 사용할 때마다, 당신은 단지 "보호"를 필요가있다 액세스를 제한하려는 controller#actions 이 작업을 수행하기 위해 authenticate_user! 도우미 메서드를 사용할 수 있다는 점이

이 외에도 컨트롤러에 current_user을 호출 할 수 있습니다 (이제는 사용자를 설정하지 않아도됩니다) :

#app/controllers/posts_controller.rb 
class PostsController < ApplicationController 
    def new 
     @post = current_user.posts.new 
    end 

    def create 
     @post = current_user.posts.new post_params 
     @post.save 
    end 

    private 

    def post_params 
     params.require(:post).permit(:x, :y, :z) 
    end 
end 
+1

정확히 내가 무엇을 찾고 있었습니까. 감사. :) – Amey