简体   繁体   English

每个循环使用from到

[英]rails each loop with from to

In my controller i fetch 9 row's for object organizations. 在我的控制器中,我为对象组织提取了9行。

  @organizations = Organization.where(parent_id: 1).order(city_id: :asc, is_vip: :desc, title: :asc).limit(25).sample(9)

and then in view i must separate this 9 value's to 3 view loops, like first .each do if for row's 1-3, second for 4-6, third 6-9 然后在视图中我必须将这9个值分隔为3个视图循环,如第一个。如果行为1-3,则为4-6,第三个为6-9

and i try so: 我试试这样:

- @organizations[0..2].each do |org|
...
- @organizations[3..5].each do |org|
...
- @organizations[6..8].each do |org|
...

but it seems that i do something wrong, but what exactly? 但似乎我做错了什么,但到底是什么? and how to do it right? 以及如何正确行事?

Not sure why your data is duplicated. 不确定为什么您的数据是重复的。 But you can use the following method for splitting the array into slices 但您可以使用以下方法将数组拆分为切片

you can use each_slice 你可以使用each_slice

@organization.each_slice(3) do |sliced_orgs|
end

Some documentation here 这里有一些文档

First I don't really get why you use .limit(25).sample(9) , you could limit your results to 9 already. 首先,我不明白为什么你使用.limit(25).sample(9) ,你可以将你的结果限制为9。 But maybe you have some use of the random factor introduced by sample? 但也许你有一些使用样本引入的随机因素? Strange. 奇怪。

Other than that, 除此之外,

@organizations[0..2].each do |org|
    puts org
end
...

should work perfectly fine. 应该工作得很好。 If the data is repeated it is because you have multiple times the same entry in your model. 如果重复数据,那是因为您在模型中有多次相同的条目。 sample(9) is taking random unique entries and @organizations[0..2] is a fixed range returning an array or nil. sample(9)采用随机唯一条目, @organizations[0..2]是返回数组或nil的固定范围。 (Rubydoc : ary[range] → new_ary or nil ) (Rubydoc: ary[range] → new_ary or nil

In short, nothing wrong with the code but probably somewhere in your data/logic. 简而言之,代码没有任何问题,但可能在数据/逻辑中的某个地方。

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

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