2

I have a standard posts controller with an index action.

At the moment, I am routing this as the home page /, as well as the posts page /posts

class PostsController < ApplicationController

    def index
    # Logic and finds here
    end

end

And in my routes.rb file:

root to: "posts#index"
get "/posts" => "posts#index"

However, in my view, I would like to lay things out slightly differently depending on whether the route is /posts or just /. Is this possible? And if so, what is the best practice for this?

I was thinking about creating another action in the posts controller, but then I would be replicating the logic, already defined in my index action - which I want to avoid.

I basically want to use the same content, but show a different view.

Any advice or help is greatly appreciated.

Thanks, Michael.

Michael Giovanni Pumo
  • 14,338
  • 18
  • 91
  • 140
  • While it's possible, I think it would be more readable etc. if you use separate actions for these routes. You can put your logic from `index` action in separate private method in controller. – Marek Lipka Apr 29 '14 at 10:15

2 Answers2

3

One solution apart from using different controllers/actions would be to pass an additional parameter in from your router:

root to: "posts#index", source: 'home'
get "/posts" => "posts#index"

Then in your controller you can do this:

class PostsController < ApplicationController
  def index
    # Logic
    render(params[:source] || 'index')
  end
end

It will render the home template when the user entered through the root path, and the index template otherwise.

fivedigit
  • 18,464
  • 6
  • 54
  • 58
1

For the current scenario you can use this

In your action use

request.fullpath

This will catch the current uri, you can use this to implement things or in rails 4 you can also use

request.original_url

to fetch the URL, this question explains the use in details

Community
  • 1
  • 1
Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78