与user / user_id / resource / new相比,更新仅显示资源/新的路由

时间:2014-09-19 22:06:22

标签: ruby-on-rails ruby-on-rails-4 devise routes

我正在使用rails 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操作上的网址为 - > https://localhost:3000/bloggers/1/articles/new但我想表明 https://localhost:3000/articles/new,因为帖子上的新操作应始终与current_user相关联。

我认为这是可能的,但不知道如何做到这一点。

也是user has_many posts

请帮帮忙?

1 个答案:

答案 0 :(得分: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

这里的底线是,无论何时你想使用经过验证的区域(特别是使用Devise),你只需要保护&#34;要限制访问权限的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