3

如果通过此“.any”调用找到帖子,如何接收帖子的 ID ?

<% if @posts.any? {|p| p.title == my_title} %>
4

3 回答 3

6

你可能应该这样做:

<% if (post = @posts.detect {|p| p.title == my_title} ) %>
  Post ID: <%= post.id %>
<% end %>
于 2011-08-03T14:55:14.777 回答
1

Any 不会返回任何东西,除了trueor false

http://www.ruby-doc.org/core/classes/Enumerable.html#M001500

如果您想退回某些东西,请使用select

http://www.ruby-doc.org/core/classes/Enumerable.html#M001488

于 2011-08-03T14:55:12.887 回答
0

执行以下操作,如果条件为真,则获取值。但是,以下方式仅将 post_id 设置为最后匹配的帖子,如果您想要所有这些,则将 post_id 设置为数组:

<% post_id = nil%>
<% if @posts.any? {|p| post_id = p.id if p.title == my_title; p.title == my_title} %>
于 2011-08-03T15:02:06.700 回答