如果通过此“.any”调用找到帖子,如何接收帖子的 ID ?
<% if @posts.any? {|p| p.title == my_title} %>
如果通过此“.any”调用找到帖子,如何接收帖子的 ID ?
<% if @posts.any? {|p| p.title == my_title} %>
你可能应该这样做:
<% if (post = @posts.detect {|p| p.title == my_title} ) %>
Post ID: <%= post.id %>
<% end %>
Any 不会返回任何东西,除了true
or false
。
http://www.ruby-doc.org/core/classes/Enumerable.html#M001500
如果您想退回某些东西,请使用select
http://www.ruby-doc.org/core/classes/Enumerable.html#M001488
执行以下操作,如果条件为真,则获取值。但是,以下方式仅将 post_id 设置为最后匹配的帖子,如果您想要所有这些,则将 post_id 设置为数组:
<% post_id = nil%>
<% if @posts.any? {|p| post_id = p.id if p.title == my_title; p.title == my_title} %>