简体   繁体   English

Rails如何使用除了id列表?

[英]Rails how to use except with a list of ids?

Example I have some ids in my application controller: 示例我的应用程序控制器中有一些ID:

@clicked = %w(32, 18, 13)

And in my controller I have: 在我的控制器中,我有:

@konkurrencer = Konkurrencer.find(:all, :order => 'created_at DESC').paginate(:page => params[:page], :per_page => 5)

How do I remove the Konkurrencer with the IDS 32, 18 and 13 from @konkurrencer? 如何从@konkurrencer中删除IDS 32,18和13的Konkurrencer?

And how to implement a clicked attribute (boolean) to konkurrencer. 以及如何为konkurrencer实现一个clicked属性(布尔值)。 Example then it would be possible in the loop to do <% if kon.clicked %>CLICKED<% end %> it would be true if the kon had a id in the @clicked 例如,如果kon在@clicked有一个id,那么在循环中可以做<% if kon.clicked %>CLICKED<% end %>

You could use NOT IN, I've tested without the paginate part, try and let me now if it works: 您可以使用NOT IN,我已经在没有分页部分的情况下进行了测试,如果有效,请尝试让我现在:

@konkurrencer = Konkurrencer.where("id NOT IN(?)", @clicked).order("created_at DESC").paginate(:page => params[:page], :per_page => 5)

Be sure the @clicked variable is an array as moo is too short suggests. 确保@clicked变量是一个数组,因为moo太短了。

你可以使用delete_if

As ghr mentioned, you could use delete_if but if you have a bunch of ids, the condition logic might get long. 正如ghr所提到的,你可以使用delete_if但是如果你有一堆id,那么条件逻辑可能会变长。 As an alternative, but somewhat expensive solution, you could just "subtract" the target items by building another collection: 作为替代方案,但有点昂贵的解决方案,您可以通过构建另一个集合来“减去”目标项:

 @konkurrencer = Konkurrencer.find(:all, :order => 'created_at DESC') - Konkurrencer.find(32,18,13)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM