开发者

Rails "any?" instance method callback?

开发者 https://www.devze.com 2023-03-25 04:30 出处:网络
How to receive the post\'s ID, if post is found via开发者_运维知识库 this \'.any\' call? <% if @posts.any? {|p| p.title == my_title} %>

How to receive the post's ID, if post is found via开发者_运维知识库 this '.any' call?

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


You should probably do it like this:

<% if (post = @posts.detect {|p| p.title == my_title} ) %>
  Post ID: <%= post.id %>
<% end %>


Any won't return anything except true or false.

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

if you want to something to be returned, use select

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


Do something like the following, get the value if the condition is true. However the following way only set the post_id to the last matched post, if you want all of them, then set post_id as array:

<% post_id = nil%>
<% if @posts.any? {|p| post_id = p.id if p.title == my_title; p.title == my_title} %>
0

精彩评论

暂无评论...
验证码 换一张
取 消