So I've been struggling a little in trying to understand exactly what I can do with a link_to in Rails. Some of what I've found is old, some is new, some is very different looking from what I've got. Specifically I'm trying to have two links in a view. One is "Add 1", one is "Minus 1". When I get to the controller I want to then add or subtract one from my model based on which link was used. Here are the links:
<%= link_to "Add 1", item, method: :put, title: item.name %>
<%= link_to "Minus 1", item, method: :put, title: item.name %>
My controller (item controller) method is:
def update
@item = current_user.item.find(params[:id])
@item.quantity += #+1 or -1 depending on what is passed
if @item.save
flash[:success] = "Item updated."
end
redirect_to current_user
end
Since I'm calling link_to with a :put I am not quite sure how to distinguish which :put is which, as both links are the same except for the name of the link. I think I'm identifying the specific item with the title: item.name
parameter. Is it identified simply by item
path? Should I change the ":title" to a "+1" or "-1"? I'd really appreciate clarification as this is confusing the hell out of me. I also noticed in the docs "html options" vs "url options" but I couldn't decipher the differences? Thanks!
You can pass additional parameters in the URL:
<%= link_to "Add 1", item_path(item, perform: 'add'), method: :put %>
<%= link_to "Sub 1", item_path(item, perform: 'sub'), method: :put %>
def update
@item = current_user.item.find(params[:id])
params[:perform] == 'sub' ? @item.quantity -= 1 : @item.quantity += 1
if @item.save
flash[:success] = "Item updated."
end
redirect_to current_user
end
Or perhaps add member actions to your item resource
:
resources :items do
member do
put 'sub'
put 'add'
end
end
link_to "Add 1", [:add, item], method: :put
link_to "Sub 1", [:sub, item], method: :put