Dynamic Paths

Hey there,

I’m in the muck of a major rails project, and need a bit of advice. Google isn’t much help in this case, so I came here.

I’m trying to set up a URL structure as follows:

url.com/username/blog/post_id

where the user has_many posts and the post belongs_to user. I’m using the friendly_id plugin to enable easy lookup with the user’s username, and I would like to have the blog paths automatically retrieved, instead of getting a path error (as such):

ActionView::TemplateError (post_url failed to generate from {:controller=>“posts”, :user_id=>#<Post id: 1, user_id: 5, title: “Rock and Roll”, body: “This is my blog post body.”, created_at: “2009-12-03 15:40:06”, updated_at: “2009-12-03 15:40:06”>, :action=>“show”}, expected: {:controller=>“posts”, :action=>“show”}, diff: {:user_id=>#<Post id: 1, user_id: 5, title: “Rock and Roll”, body: “This is my blog post body.”, created_at: “2009-12-03 15:40:06”, updated_at: “2009-12-03 15:40:06”>}) on line #3 of app/views/posts/edit.html.erb:

One strategy that I’ve tried is to lookup the user, and then filter the posts by that user, but no luck thus far on making the paths work. Before I write my own link helpers, do you have any ideas?

Thanks!

Nicholas Young
nicholas@nicholaswyoung.com
615.727.2645 (Cell)
615.829.6687 (Main)
http://nicholaswyoung.com

Maybe something like this would work:

in the user model:
has_many :posts, :dependent => :destroy
def to_param
  username
end

in the route:
map.resources :posts, :path_prefix => ":username"

Then in the view:
post_url(post, :username => "donaldduck")

In the controller:
user = User.find_by_username params[:username]
@post = user.posts.find(params[:id])

You’ll have to at least show the relevant parts of your config/routes.rb file to get any decent help. As it is, the post_url doesn’t appear to be set up to expect your user_id and post_id properly. If you look closely, you’ll see that :user_id is associated to a Post object which is probably wrong.

-Rob

Rob Biedenharn http://agileconsultingllc.com

Rob@AgileConsultingLLC.com