如果不满足要求,则将用户重定向到不同的页面

时间:2014-07-17 18:54:56

标签: ruby-on-rails

我为管理员和用户设置了角色。但是,角色的权限仅用于编辑目的。管理员可以编辑所有内容,用户只能编辑属于他们的内容。

我有一个Subscriptions表,显示哪个用户基于cancelled表订阅了该网站。我有一个对话收件箱,我想限制对它的访问。如果在订阅表中找到用户cancelled列为NULL,则该用户被授予查看对话页面的权限。但是,如果用户不符合该要求,则应自动转发到我们的注册页面以支付订阅费用。

有人知道如何实现这个目标吗?

对话控制器:

 def index
    @user = current_user
    sentbox_page = params[:page] if params[:sentbox].present?
    inbox_page = params[:page] if params[:inbox].present?
    mailbox = @user.mailbox
    @inbox = mailbox.inbox.paginate(:page => inbox_page, :per_page => 5)
    @sentbox = mailbox.sentbox.paginate(:page => sentbox_page, :per_page => 5)
    render layout: 'new_application'
  end

  def show
    user = current_user
    @receipts = conversation.receipts_for(user).paginate(:page => params[:page], :per_page => 5)
    @conversation.receipts.recipient(user).update_all(is_read: true)
    respond_to do |format| 
      format.html {render layout: 'new_application'}
      format.js {}
    end
  end

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

class ConversationsController < ApplicationController
  before_filter :check_has_access

  # [...]

  protected
  def check_has_access
    if Subscription.exists?(user_id: current_user.try(:id) || -1, cancelled: nil)
      # has access
      return true
    else
      redirect_to signup_path
      return false
    end
  end

check_has_access的简短版本:

def check_has_access
  redirect_to(signup_path) unless Subscription.exists?(user_id: current_user.try(:id) || -1, cancelled: nil)
end

答案 1 :(得分:1)

这将是before_filter

class ConversationsController < ApplicationController
  before_filter :authorize, only: [:index, :show]
  ...
end

class ApplicationController < ActionController::Base

  def authorize
    sub = Subscription.where('user_id = ?', current_user.id).first
    return if sub && sub.cancelled == nil
    redirect_to :root, alert: "Please sign up to be able to do this"
  end
end