Reputation: 24886
I have a set of nested resources -- :users and :messages.
resources :users, :only => [:show,:index] do
resources :messages
end
And also a formtastic form in the "new.html.haml" template for the Message model and it needs to use these resources:
=semantic_form_for [@user,@message] do |f|
=f.input :title
The problem is in the actual action path that is generated from [@user,@message], and it looks like this:
/users/4cdc7f9dfae434029a0000aa/messages
This is wrong because I am using a named route, so this should look like "/users/nickname/messages"
How can I make sure that @user produces a proper path output?
Edit: Here is the name routes I am using to slugify the user.
match "/users/:nickname/messages" => "messages#index"
match "/users/:nickname/messages/new" => "messages#new", :as=>:new_message
match "/users/:nickname/messages" => "messages#create", :as=>:create_message
Upvotes: 1
Views: 691
Reputation: 14973
I guess what you want is to use the nickname as the url slug. What you need for that is just the regular nested resources;
# in routes.rb
resources :users do
resources :messages
end
which would give you the same routes except they would have :id
instead of :nickname
in there.
Now for the actual trick that lets you use the user's nickname as the url identifier:
# user.rb
class User < ActiveRecord::Base
def to_param
self.nickname
end
end
You would automatically get the nickname in the url, and have it passed on to your controllers as params[:id]
so you have to act accordingly in your controller
# users_controller.rb
…
def show
@user = User.find_by_nickname(params[:id])
end
…
Upvotes: 4
Reputation: 37357
This should do the trick
=semantic_form_for :message, :url => create_message_path(:nickname => @user.nickname) do |f|
# ...
Upvotes: 0