Tom Maxwell
Tom Maxwell

Reputation: 9573

Rails before_filter to check for attribute on show action

In the show action for my Products model, I need to check for two things:
1. That the user_id associated with the product model instance is the same as the id of the current_user
2. That the braintree_customer_id of the current user is nil.

If the user accessing the show page for a product is both the creator of the product and has a nil braintree_customer_id, I need to do some action. I just haven't really worked with before_filters and don't know how to write this. Here's my show action:

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

Upvotes: 0

Views: 197

Answers (2)

Thorin
Thorin

Reputation: 2034

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

Upvotes: 0

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

In products controller add this

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

Upvotes: 1

Related Questions