【问题标题】:Rails "any?" instance method callback?导轨“任何?”实例方法回调?
【发布时间】:2011-08-03 14:51:42
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails callback any


    【解决方案1】:

    你应该这样做:

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

    【讨论】:

      【解决方案2】:

      除了truefalse,任何都不会返回任何内容。

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

      如果您想退货,请使用select

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

      【讨论】:

        【解决方案3】:

        执行以下操作,如果条件为真,则获取值。但是下面的方法只是把 post_id 设置为最后一个匹配的帖子,如果你想要所有这些,那么将 post_id 设置为数组:

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

        【讨论】:

          猜你喜欢
          • 2015-03-14
          • 2016-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多