In a view I can do this and the link works fine:
<%= link_to "Most popular comment", comment_path( Comment.find(5) ) %>
So I know that my routes are set up to show an individual comment record via comment_path(). However when I try this:
<%= link_to "Most popular comment", comment_path( @post.comments.order("vote_cnt DESC").first )
I get a “No route matches {:action=>"show", :controller=>"comments"}” error. But I know this not an accurate error description because the first link_to() statement listed above works. I’ve confirmed the route exists – from rake routes I get this:
comment GET /comments/:id(.:format) {:action=>"show", :controller=>"comments"}
In IRB I can see that the two statements I’m passing to comment_path() both generate the same class, namely “Comment“:
irb(main):022:0> top_comment = post.comments.order("vote_cnt DESC").first
Comment Load (0.6ms) SELECT "comments".* FROM "comments" WHERE "post_id" = 2 ORDER BY vote_cnt DESC LIMIT 1
=> #<Comment id: 5, heading: nil, body: nil, user_id: 5, created_at: "2012-02-03 01:23:30", updated_at: "2012-02-03 01:23:30",vote_cnt: 0>
irb(main):023:0> top_comment.class
=> Comment(id: integer, heading: string, body: text, user_id: integer, created_at: datetime, updated_at: datetime, vote_cnt: integer)
irb(main):024:0> comment_5 = Comment.find(5)
Comment Load (3.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = $1 LIMIT 1 [["id", 5]]
=> #<Comment id: 5, heading: nil, body: nil, user_id: 5, created_at: "2012-02-03 01:23:30", updated_at: "2012-02-03 01:23:30", vote_cnt: 0>
irb(main):025:0> comment_5.class
=> Comment(id: integer, heading: string, body: text, user_id: integer, created_at: datetime, updated_at: datetime, vote_cnt: integer)
If both statements generate the same class of object, how can link_to() work with one and cause a route error on the other, especially when both resolve to the same exact record? I tried:
<% top_comment = post.comments.order("vote_cnt DESC").first %>
<%= link_to "Most popular comment", comment_path( top_comment )
and that generates the same “No path matches…” error.
Any ideas what is going on here? It seems that link_to() works well with a record that comes from a straight up query against a table, but errors out on that same record if was retrieved via an ActiveRecord::Relation action. Why? How can that be?
[converting my comment above into an answer]
Sorry guys – programmer logic error.
I tried “rkb”s suggestion of …
first.id, and got an error saying I can’t get the ID of a nil object. Thislink_tocall was in a loop:Since they are recent posts, one of them didn’t have any comments. Duh! My code should check for that first.
My bad. However, it is very frustrating that link_to won’t give you a clear indication that you have passed it a nil object. “No route matches…”?!?!?! Pretty poor error message for the situation!