I have a gem which is essentially just a bunch of ActiveRecord::Base classes in the gems namespace. For all of them I get the same type of problem. I have the model…
module MyGem
class User < ActiveRecord::Base
...
end
end
Then in my app I have the routes…
resources :users
What gets screwed up is in the link_to…
<% @users.each do |user| %>
<td><%= link_to 'Show', user %></td>
<% end %>
I get…
undefined method `my_gem_user_path' for #<#<Class:0x0000000305f728>:0x00000003055408>
I’ve tried various things in routes.rb, but I’m thinking the solution may be to configure the model/link_to to call user_path(user) instead of my_gem_user_path(user) by default. I just don’t know how, if at all possible, to do this.
Anybody know the best practice here?
I think the best practice here is to namespace your routes. Your class is namespaced as MyGem::User.
#link_touses#polymorphic_pathto query the class for its class name and then calls#underscorizeon that class name to get the path, so it assumes that the path will be my_gem_user_path, not user_path. That means the resources call should be wrapped like so:Then, my_gem_user_path will resolve to the MyGem::UsersController. Make sure your controller is namespaced like that as well. If you don’t want the route to resolve to that controller, you can provide the controller name as an option to #resources.
edit: That’s interesting, I didn’t think it would run into that problem. There may still be some configuration to fix that, so I wouldn’t mark this as solved yet. You can always replace the polymorphic_path (which is what is getting called when you use the resource-oriented path like above) with named routes. For example, instead of
link_to “User”, user
you can always explicitly use
link_to “User”, my_gem_user_path
When you use RESTful routes in your routes.rb file (with the #resources method), it provides you with those named routes.
For the form_for, the syntax is slightly different:
becomes
for a new form. For an edit form, it would be
Does that make sense? Here’s a link to the documentation for form_for http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for