2014-09-19 78 views
1

我使用的轨道4一起谋害我routes.rb写着:更新的路线只显示资源/新相比,用户/ USER_ID /资源/新

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,但我想显示 https://localhost:3000/articles/new,因为该帖子的新操作应始终与current_user关联。

我会想象这是可能的,但不知道如何去做。

也是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 2014-09-20 20:27:19