如何检查值是否在值数组中找到

tan*_*nya 18 ruby ruby-on-rails

我想执行if条件,其中,如果linkedpub.LPU_ID在值数组(@associated_linked_pub)中找到,则执行一些操作.

我尝试了以下但语法不正确.

任何建议都是最受欢迎的......谢谢

<% for linkedpub in Linkedpub.find(:all) %>
   <% if linkedpub.LPU_ID IN @associated_linked_pub  %>
       # do action
   <%end%>
<%end%>
Run Code Online (Sandbox Code Playgroud)

Jit*_*its 37

您可以使用 Array#include?

所以...

if @associated_linked_pub.include? linkedpub.LPU_ID
  ...
Run Code Online (Sandbox Code Playgroud)

编辑:

如果@associated_linked_pub是ActiveRecord对象列表,请尝试以下方法:

if @associated_linked_pub.map{|a| a.id}.include? linkedpub.LPU_ID
  ...
Run Code Online (Sandbox Code Playgroud)

编辑:

更详细地看一下你的问题,看起来你正在做的是非常低效和不可扩展.相反,你可以......

对于Rails 3.0:

Linkedpub.where(:id => @associated_linked_pub)
Run Code Online (Sandbox Code Playgroud)

对于Rails 2.x:

LinkedPub.find(:all, :conditions => { :id => @associated_linked_pub })
Run Code Online (Sandbox Code Playgroud)

Rails将自动创建SQL IN查询,例如:

SELECT * FROM linkedpubs WHERE id IN (34, 6, 2, 67, 8)
Run Code Online (Sandbox Code Playgroud)