Reputation: 1885
I have a few different links, that do the same thing except for one minor difference. Is it possible to link them all to the same path, but with different params that change the behavior of that one minor difference in the controller?
I was thinking of something like this:
view
<%= link_to "Link-A", link_path(@user), @x = 1 %>
<%= link_to "Link-B", link_path(@user), @x = 2 %>
users_controller.rb
def link
@user = User.find(params[:id])
#code that should be executed for both links
if @x == 1
#do something
elsif @x == 2
#do something else
end
end
I know this specific code probably isn't even close to being correct, but hopefully it makes clear what I'm trying to do.
Upvotes: 3
Views: 2711
Reputation: 7405
View:
<%= link_to "Link-A", link_path(@user, x: 1) %>
<%= link_to "Link-B", link_path(@user, x: 2) %>
Controller:
def link
@user = User.find(params[:id])
x = params[:x]
#code that should be executed for both links
if x == 1
#do something
elsif x == 2
#do something else
end
end
Upvotes: 4
Reputation: 664
In the view, send also the control params
<%= link_to 'Link', request.parameters.merge({:x => 'special'}) %>
In the controller, check the params then start then logic.
if params.fetch(:x)
# A different logic
end
Upvotes: 1
Reputation: 3019
I think you should add your param as an option to your path like so:
<%= link_to "Link-A", link_path(@user, x: "1") %>
then in controller you can do:
...
@input = params[:x]
if @input ...
...
Upvotes: 4