Ruby-on-rails 我将如何检查值是否在值数组中找到
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6350035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would I check if a value is found in an array of values
提问by tanya
I want to perform an if condition where, if linkedpub.LPU_IDis found in an array of values(@associated_linked_pub), do some action.
我想执行一个 if 条件,如果linkedpub.LPU_ID在一组值(@associated_linked_pub)中找到,则执行一些操作。
I tried the following but the syntax is not correct.
我尝试了以下但语法不正确。
Any suggestion is most welcomed..Thanks a lot
任何建议都是最受欢迎的..非常感谢
<% for linkedpub in Linkedpub.find(:all) %>
<% if linkedpub.LPU_ID IN @associated_linked_pub %>
# do action
<%end%>
<%end%>
回答by Jits
You can use Array#include?
您可以使用 Array#include?
So...
所以...
if @associated_linked_pub.include? linkedpub.LPU_ID
...
Edit:
编辑:
If @associated_linked_pubis a list of ActiveRecord objects then try this instead:
如果@associated_linked_pub是 ActiveRecord 对象列表,请尝试以下操作:
if @associated_linked_pub.map{|a| a.id}.include? linkedpub.LPU_ID
...
Edit:
编辑:
Looking at your question in more detail, it looks like what you are doing is VERY inefficient and unscalable. Instead you could do...
更详细地查看您的问题,看起来您正在做的事情非常低效且不可扩展。相反,你可以做...
For Rails 3.0:
对于 Rails 3.0:
Linkedpub.where(:id => @associated_linked_pub)
For Rails 2.x:
对于 Rails 2.x:
LinkedPub.find(:all, :conditions => { :id => @associated_linked_pub })
Rails will automatically create a SQL IN query such as:
Rails 会自动创建一个 SQL IN 查询,例如:
SELECT * FROM linkedpubs WHERE id IN (34, 6, 2, 67, 8)
回答by bigtex777
linkedpub.LPU_ID.in?(@associated_linked_pub.collect(&:id))
Using in?in these cases has always felt more natural to me.
in?在这些情况下使用对我来说总是更自然。
回答by Sameer C
@associated_linked_pub.collect(&:id).include?(linkedpub.LPU_ID)
回答by John Bachir
if @associated_linked_pubis an array, try
如果@associated_linked_pub是数组,请尝试
if @associated_linked_pub.include?(linkedpub.LPU_ID)

