Ryan.lay
Ryan.lay

Reputation: 1761

Rails conditional redirect

I'm trying to setup a redirect for new users to a help page, similar to the way stack overflow presents a how to ask page when new users tries to ask a new question.

PostsController

  def new
    if current_user.posts_count < 5
      redirect_to newbieadvice_path
    else
      @question = Question.new
    end
  end

Problem is, similar to Stack Overflow, I have a "proceed to new post" button on the help page that leads back to posts#new, which then loops back to the help page because the current_user.posts_count is still < 5.

How do I bypass the redirect once the user is on the help page?

From what I read, there are two ways I can go about it:

1. Use link_to_if in the view

<%= link_to_if current_user.posts_count < 5 ... %>

Which unfortunately enables users to bypass the help page by typing the url directly.

2. Use an advices counter cache in the db

if current_user.advices_count < 5

and increment the count when the user visits the help page. I'm not certain that this is the best approach.

So I need a way to 1. Redirect new users to a help page 2. After reading the help page users can proceed back to posts#new without the redirect

Any thoughts?

Upvotes: 0

Views: 698

Answers (2)

Zakwan
Zakwan

Reputation: 1072

use request.referer. so in your controller change as following:

if URI(request.referer).path != newbieadvice_path && current_user.posts_count < 5

Upvotes: 2

nickcen
nickcen

Reputation: 1692

  1. generate a random token inside the help page, and add this token as a param to the "proceed to new post" link, then insider your post controller, do a verification of this token.

  2. check the "HTTP_REFERER" value of the http request header, request.env['HTTP_REFERER'], and see whether the user is coming from the help page.

Upvotes: 1

Related Questions