Haseeb Ahmad
Haseeb Ahmad

Reputation: 8740

Send a variable from one action to another in ruby on rails

Code in controller is

if params["type"] == "user"
  respond_to do |format|
    format.html { redirect_to home_user_path, notice: "abc" }
  end

If I send variable with notice then work fine but I want to send with my own key like

format.html { redirect_to home_user_path, search: "abc" }

It doesn't recieve there

Upvotes: 1

Views: 1218

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

You must remember that you're not "sending" a variable to another action; you're invoking another action, and populating it with a variable (data):


1. Instance Variable

You can set an instance variable, which will then be available in the next action:

 def your_action
   @search = "abc"
   respond_to do |format|
     format.html { redirect_to home_user_path } #-> @search will be available in the other view
   end
 end

2. Sessions

You're currently trying to use sessions to populate the data:

def your_action
   redirect_to home_user_path, search: "abc"
end

#app/views/controller/your_action.html.erb
<%= flash[:search] %>

3. URL

Finally, you can set the value in the URL through your routes:

def your_action
   redirect_to home_user_path(search: "abc") #-> you'll probably need to set the user object too, judging from the route name
end

This should populate your route with some GET request params: url.com/action?param=value


The underpin of all of this, as mentioned, is that you're not sending a variable, you'll be initializing it in your current controller action, and then having the next action call it.

Upvotes: 1

Max Williams
Max Williams

Reputation: 32955

This is a problem with Ruby's optional braces: sometimes it's hard to see which method call something is being treated as an argument to.

Try this instead:

format.html { redirect_to home_user_path(search: "abc") }

this will redirect to home_user_path and set params[:search] to "abc".

Upvotes: 1

Related Questions