【发布时间】:2012-03-08 14:45:40
【问题描述】:
在一个视图中我可以做到这一点并且链接工作正常:
<%= link_to "Most popular comment", comment_path( Comment.find(5) ) %>
所以我知道我的路线设置为通过comment_path() 显示个人评论记录。但是,当我尝试这样做时:
<%= link_to "Most popular comment", comment_path( @post.comments.order("vote_cnt DESC").first )
我收到“No route matches {:action=>"show", :controller=>"comments"}”错误。但我知道这不是一个准确的错误描述,因为上面列出的第一个 link_to() 语句有效。我已经确认路线存在 - 从rake routes 我得到这个:
comment GET /comments/:id(.:format) {:action=>"show", :controller=>"comments"}
在 IRB 中,我可以看到我传递给 comment_path() 的两个语句都生成相同的类,即“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)
如果两个语句都生成相同的对象类,link_to() 如何与一个对象一起工作并在另一个对象上导致路由错误,尤其是当两个语句都解析为相同的确切记录时?我试过了:
<% top_comment = post.comments.order("vote_cnt DESC").first %>
<%= link_to "Most popular comment", comment_path( top_comment )
这会产生相同的“没有路径匹配...”错误。
有什么想法吗? link_to() 似乎可以很好地处理来自对表的直接查询的记录,但如果通过 ActiveRecord::Relation 操作检索到同一记录,则会出错。为什么?怎么可能?
【问题讨论】:
-
试试
@post.comments.order("vote_cnt DESC").first.id? (该查询代码可能应该在控制器中,但这是另一个问题。) -
你是按资源定义评论路由还是匹配?
-
对不起,程序员逻辑错误。我尝试了“rkb”对 ...first.id 的建议,但收到一条错误消息,提示我无法获取 nil 对象的 ID。此 link_to 调用位于“@top_ten_posts each do |post|”中环形。由于它们是最近的帖子,因此其中一个没有任何 cmets。呸!我的代码应该先检查一下。我的错。然而,很令人沮丧的是,link_to 不会给你一个明确的指示,表明你已经向它传递了一个 nil 对象。 “没有路线匹配......”?!?!?!非常糟糕的错误消息。
标签: ruby-on-rails activerecord ruby-on-rails-3.1 routes link-to