Rails before_filter检查show动作的属性

时间:2014-09-04 09:07:41

标签: ruby-on-rails

在我的产品模型的show动作中,我需要检查两件事:1。与产品模型实例关联的user_id与current_user的id相同
2。当前用户的braintree_customer_id为零。

如果访问产品展示页面的用户既是产品的创建者,又是nil braintree_customer_id,我需要采取一些措施。我只是没有真正使用before_filters而且不知道如何写这个。这是我的节目动作:

def show
    @product = Product.find(params[:id])
    respond_to do |format|
      format.html
    end
  end

2 个答案:

答案 0 :(得分:1)

在产品控制器中添加此

before_filter :check_id, only: [:show]

def check_id
  @product = Product.find(params[:id])
  if @product.user == current_user and current_user.braintree_customer_id.blank?
    # do something
  else
    # do something else
  end
end

答案 1 :(得分:0)

You can try something like this

before_filter :check_ids, :only => [:show]

def check_ids
   @product = Product.find(params[:id])
   if @product.user_id == current_user.id and current_user.braintree_customer_id.blank?
      return true 
      # this will allow you to load show method
   else
    # show some error message
    return false
  end
end