Tom Caraccia
Tom Caraccia

Reputation: 21

Rails Controller knowing which action brought me here

The scenario is this: I have 2 Model-View-Controllers , A and B.

In A's index.html.erb, I have a link to B's new.html.erb, that looks like /a/1/b/new. B can also be displayed by doing /b/new.

In B's new method is there a way to tell I got there from a?

I need to do if came from A, do some, otherwise don't.

Thanks

Upvotes: 0

Views: 55

Answers (3)

Richard Peck
Richard Peck

Reputation: 76774

FYI

If you'd like to know the name of your controller & action, you can use the two Rails helpers called action_name (now action it seems) and controller_name

Whether this will help you directly, I'm not sure

--

Referral

In B's new method is there a way to tell I got there from a?

I don't know if this will solve your issue as well as @sonnyhe2002's answer, but if you're requesting B from a nested resource, you could play with the params hash to achieve the functionality you desire

If your routes are like this:

#config/routes.rb
resources :a do
   resources :b #-> domain.com/a/:a_id/b/new
end

This will mean if you render the b#new action as part of your nested route, you will have the variable params[:a_id] available, which means you'll be able to test if it's there in your b controller action:

#app/controllers/b_controller.rb
def new
   if params[:a_id]
      # logic
   else
      # logic
   end
end

It's a different way of looking at it

Upvotes: 0

The Lazy Log
The Lazy Log

Reputation: 3574

If your action is processing the request with A resource, you should be able to retrieve the a_id in the params hash. Here is the method I often use in my app:

class BController < ApplicationController
    def new
       if params[:a_id].present?
           #do something with A here
       else
           #do something otherwise
       end
    end
end

If you want to be sure, run rake routes in your console to see how the requests look like. I imagine you would see a route like this:

a/:a_id/b/new

and another route like this

/b/new

Upvotes: 0

sonnyhe2002
sonnyhe2002

Reputation: 2121

You can use the refer

refer_hash = Rails.application.routes.recognize_path(request.referrer)

now you can check the previous controller by

refer_hash[:controller]

and action by

refer_hash[:action]

So in the end you will have code like

refer_hash = Rails.application.routes.recognize_path(request.referrer)
if refer_hash[:action] == 'index' && refer_hash[:controller] == 'A'
    # Do something
else
    # Do something else
end

Upvotes: 2

Related Questions