0

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!

MCP
  • 4,436
  • 12
  • 44
  • 53

1 Answers1

2

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
osahyoun
  • 5,173
  • 2
  • 17
  • 15
  • what is `title: item.name` doing? – Zippie Apr 06 '13 at 07:47
  • I thought the "title: item.name" was allowing me to identify the specific item in the controller... – MCP Apr 06 '13 at 07:50
  • @osahyoun - The link_to examples worked. THANKS A TON. For clarification. "item_path" is obviously the path, then you're passing in an instance and a hash? (with item being the instance and "perform:'sub'" the hash) Between the two examples you posted, is one preferred? Thanks again! – MCP Apr 06 '13 at 07:57
  • @MCP exactly right. With name/value pairs passed in the hash, becoming URL params. – osahyoun Apr 06 '13 at 08:02