Let’s say I have methodA
def methodA
note = Note.find(params[:id])
note.link = params[:link]
note.linktype = params[:linktype]
note.save
redirect_to(notes_url)
end
When I call this method from a view like this, it works fine
<%= link_to image_tag(w.link, :border =>0), methodA_path(:linktype => w.linktype, :link => w.link, :id => @note.id) %>
But, if I call the method from another method in the same controller like this:
def methodB
...
methodA(:id => params[:id], :link => link, :linktype => "image")
end
I get this error:
wrong number of arguments (1 for 0)
The parameters that methodA is getting are still the same parameters that methodB got, not the ones that I’m sending from methodB. How do I get around this problem? Thank for reading.
Several things:
method_arather thanmethodA.methodAis a controller action. If you look at your method signature, you’re not actually defining any method parameters. That’s a good thing: actions don’t take any.paramscall in themethodAaction is not accessing method parameters, but is access the Rails requestparamshash.methodA_path, which is generating the URL. This is a shortcut tourl_forthat automatically fills in some parameters for you (the other ones are in the hash you’re passing). This method was automatically generated for you from your routes. Do arake routesfrom the root of your app for a little more information.methodB, which is probably unwise, you don’t need to pass it the parameters. SincemethodBis also an action being called in its own request cycle, theparamshash is still available tomethodA, and it will find all of those things just fine. I’d suggest, however, extracting any common functionality into a third helper method and calling that from each action; calling actions from other actions feels like a code smell to me.A bit of a summary:
methodAandmethodA_pathare different methods. The former takes no parameters but accesses the Rails request parameters hash, while the latter takes parameters to pass tourl_for.This is all pretty basic, so I strongly suggest you read Agile Web Development with Rails (3rd edition for Rails 2, 4th for Rails 3).