Rails —— 查找到处都有 id 的条件

发布于 2024-09-12 05:49:09 字数 465 浏览 2 评论 0原文

我从我的模型中提取了这个查找条件,目前看起来像这样。

 @major_set = Interest.find(:all, :conditions => {:id => 1..21})

我想添加一些我刚刚添加的更多个人 ID,例如 120...130。我尝试这样做...

 @major_set = Interest.find(:all, :conditions => {:id => 1..21, 120..130})

但收到错误。 “语法错误,意外的'}',期待 tASSOC ...ns => {:id => 1..21, 122..130})”

我如何选择多组 id 以及某些单独的 id ids,即 ( :conditions => {:id => 1..21, 121..140, 144, 155 }??

I have this find condition pulling from my model that currently looks like this.

 @major_set = Interest.find(:all, :conditions => {:id => 1..21})

I'd like to add some more individual ids that I've just added which are like 120...130. I tried to do...

 @major_set = Interest.find(:all, :conditions => {:id => 1..21, 120..130})

but got the error. " syntax error, unexpected '}', expecting tASSOC ...ns => {:id => 1..21, 122..130})"

How can I select multiple sets of id's as well as maybe some individual ids, ie ( :conditions => {:id => 1..21, 121..140, 144, 155 }??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

内心荒芜 2024-09-19 05:49:09

您可以将范围转换为数组并将它们添加在一起。例如,

@major_set = Interest.find(:all, 
    :conditions => {:id => (1..21).to_a + (120..130).to_a})

如果您想添加单独的 id,那么您只需将它们添加到数组中即可。例如

ids_to_find = (1..21).to_a + (120..140).to_a
ids_to_find << 144
ids_to_find << 145
@major_set = Interest.find(:all, :conditions => { :id => ids_to_find })

You can convert the ranges to arrays and add them together. E.g.

@major_set = Interest.find(:all, 
    :conditions => {:id => (1..21).to_a + (120..130).to_a})

If you then want to add in individual ids then you can just add them to the array. E.g.

ids_to_find = (1..21).to_a + (120..140).to_a
ids_to_find << 144
ids_to_find << 145
@major_set = Interest.find(:all, :conditions => { :id => ids_to_find })
橙幽之幻 2024-09-19 05:49:09

如果您输入 {:id =>; 1..21, 122..130} 在 irb 中你会得到一个错误,因为它不是有效的 ruby​​ 语法。这被解释为哈希,其中第一个元素是 :id => 1..21,第二个丢失了它的密钥。
为了使其成为有效的 ruby​​ 表达式,您需要输入:

{:id=>[1..21, 122..130]}

但我认为 ActiveRecord 不会接受该语法。所以你可能需要:

:conditions => "id BETWEEN 1 AND 21 OR id BETWEEN 122 AND 130"

这适用于 MySQL。我不知道它是否适用于其他数据库。

If you type {:id => 1..21, 122..130} inside irb you will get an error because it is not valid ruby syntax. This is interpreted as a hash where the first element is :id => 1..21 and the second is missing its key.
In order to make it a valid ruby expression, you would need to type:

{:id=>[1..21, 122..130]}

But I don't think that ActiveRecord will accept that syntax. So you may need to:

:conditions => "id BETWEEN 1 AND 21 OR id BETWEEN 122 AND 130"

This works in MySQL. I don't know if it will work in other databases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文