如何限制未签名用户查看某些静态页面 - Rails4

时间:2016-04-20 12:02:16

标签: ruby-on-rails-4

我是铁杆新手,非常感谢你的帮助。

  1. 我希望未签名的用户只能查看静态页面landingpg,而不能查看homepg& aboutpg
  2. 静态页面homepg& aboutpg可以被未签名的用户查看,但是现在我想限制未签名的用户查看homepg& aboutpg
  3.   可以告诉我最好的方法吗?

    class StaticPagesController < ApplicationController
      respond_to :html, :xml, :json
    
      def aboutpg
        @timelines = Timeline.order("created_at DESC")
      end
    
      def homepg
        @reviews = Review.limit(3).all
        @search = Advert.search(params[:q])
        @adverts = @search.result(distinct: true)
        @companies = Company.all
      end
    
      def landingpg 
        @signup = Signup.new
      end
    end
    

    route.rb

      root    'static_pages#landingpg'
      get     'about',                  to: 'static_pages#aboutpg'
      get     'home',                   to: 'static_pages#homepg'
    

2 个答案:

答案 0 :(得分:2)

您需要添加before_filter。

  Class StaticPagesControlle  < ApplicationController
    before_filter :not_allowed ,:only => [:homepg,:aboutpg]
      #rest is your code
   end
       #and in application controller or your StaticPageController do this
       class ApplicationController < ActionController::Base
         #define that method
         def not_allowed
           if current_user is unsigned (# here your logic for a user to be unsigend)
             render json: {
             status: 401,    
             message: 'You are not an authorised person to access this page'
            }
          end
          end

答案 1 :(得分:1)

在调用您的操作之前,请包含将运行方法的before_filterbefore_action。如果方法重定向到另一个路径,则会绕过对该操作的调用。

class StaticPagesController < ApplicationController
  respond_to :html, :xml, :json

  before_filter :user_allowed, only: [:aboutpg, :homepg]

  def aboutpg
    @timelines = Timeline.order("created_at DESC")
  end

  def homepg
    @reviews = Review.limit(3).all
    @search = Advert.search(params[:q])
    @adverts = @search.result(distinct: true)
    @companies = Company.all
  end

  def landingpg 
    @signup = Signup.new
  end

  def user_allowed
    unless current_user
      flash[:error] = "Please sign in first."
      redirect_to root_path
    end
  end
end