I am currently trying to define my first new action in Rails 3, despite various problems I think things are almost done now. However, I as a final hurdle I am struggling to send the correct parameter value to my function…
My function is defined in items_controller:
def clickcountplusone
clickeditem = Item.find(params[:id])
redirect_to clickeditem.externalurl if clickeditem.update_attribute(:click_count, clickeditem.click_count + 1)
end
routes.rb contains:
match '/items/clickcountplusone', :to => 'items#clickcountplusone'
and the view contains:
<%= link_to image_tag( item.picture.to_s + ".gif", send("items_clickcountplusone_path", item.item_name)%>
The view page itself loads correctly (the one with the link on it), but when I click on the link I get an error:
Couldn't find Item with ID=clickcountplusone
{"id"=>"clickcountplusone",
"format"=>"whatever the name is"}
and rather than going to the external page, my browser tries to load:
http://localhost:3000/items/clickcountplusone.whatever the name is
Can anyone tell me how I should be calling the function so that the ID is the item_name and the external URL is visited rather than an incorrect one on my site?
Thanks in advance
It seems like this would be a normal route, instead of a RESTful route (this is fine). There are some places you have to change.
First, in your controller’s action, you used
params[:id]which is not set actually.In this particular case, I would suggest you use
params[:item_name]instead ofidbecause you are really sending theitem_name.Item.findcould only be used if the parameter is one ofthe actual id / :all / :first / :last.You are finding by the
item_name, so you should useItem.find_by_item_nameinstead.Second, you have to update you route too (or else you would need something like /you_path..?item_name=blahblahblah which is fine too if you don’t mind)
Third, you view. IMO, most of the time if you are using
sendbut not writing library / really back end code, you probably misusing it.