3

In my controller i fetch 9 row's for object organizations.

  @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

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?

4
  • Why do you say you're doing something wrong? What is the problem you're seeing? Commented Apr 15, 2014 at 20:40
  • @IsmailBadawi data is sometime's repeated Commented Apr 15, 2014 at 20:41
  • 1
    Are you sure there isn't duplicate data in the actual result set? Commented Apr 15, 2014 at 20:44
  • @Chuck check now - no, no duplicates Commented Apr 15, 2014 at 20:53

2 Answers 2

5

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

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

Some documentation here

Sign up to request clarification or add additional context in comments.

1 Comment

is it right syntax to view? %ul - @organizations[0..2].each do |org1| %li =link_to org1.title, organization_path(org1) %p =raw "<strong>#{org1.city.name}</strong>, <br> #{org1.address}" .introtext-separator .introtext %ul - @organizations[3..5].each do |org2| %li =link_to org2.title, organization_path(org2) %p =raw "<strong>#{org2.city.name}</strong>, <br> #{org2.address}"
0

First I don't really get why you use .limit(25).sample(9), you could limit your results to 9 already. 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. (Rubydoc : ary[range] → new_ary or nil)

In short, nothing wrong with the code but probably somewhere in your data/logic.

2 Comments

I think OP wants to get nine random entries, not nine deterministic entries.
is it right syntax to view? %ul - @organizations[0..2].each do |org1| %li =link_to org1.title, organization_path(org1) %p =raw "<strong>#{org1.city.name}</strong>, <br> #{org1.address}" .introtext-separator .introtext %ul - @organizations[3..5].each do |org2| %li =link_to org2.title, organization_path(org2) %p =raw "<strong>#{org2.city.name}</strong>, <br> #{org2.address}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.