Niraj Pal
Niraj Pal

Reputation: 33

how to send parameter to the action of another controller through url in rails?

How to send parameter to the action of another controller through url in rails?

controller1:

def show
  @controller1.id = params[:controller1_id]
end

in the view of controller1:

%a.btn-general{:href => "/controller2/new/#{parameteroffirst.id}", :controller1_id @controller1.id,  :role => "button"} Add the first

how to send controller1.id to new action of controller2?

Upvotes: 0

Views: 55

Answers (2)

arieljuod
arieljuod

Reputation: 15848

A good practice in rails is to use named routes instead of string urls.

%a.btn-general{href: url_for(controller: :controller2, action: :new, id: parameteroffirst.id, controller1_id: @controller1.id), role: "button"} Add the first

It will generate an url like /controller2/new/#{parameteroffirst.id}?controller1_id=#{@controller1.id}. but you can change the route tomorrow without the need to go all over your code changing the hardcoded links.

Upvotes: 0

Mark
Mark

Reputation: 6455

If you really want to write it out like this, try changing:

:href => "/controller2/new/#{parameteroffirst.id}", :controller1_id @controller1.id

To:

:href => "/controller2/new?controller1_id=#{parameteroffirst.id}"

But it's really worth your reading up on how links are supposed to work in ruby / rails:

https://api.rubyonrails.org/v5.2.1/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Upvotes: 1

Related Questions