bandola
bandola

Reputation: 367

Rails Active Record find all including duplicates

How can I get duplicate posts in my view?

I want to be able to do something like this:

@post = post.find(1,2,1)

to return post 1 , post 2 and then post 1 (again).

realize this is a dumb question but I can't find any documentation.

Upvotes: 1

Views: 592

Answers (2)

Tam
Tam

Reputation: 12042

Although I'm not sure about the use case you can do something like:

@posts = Post.find(1,2) << Post.find(1)

of you can define this in your Post model:

def find_with_array(*args)
   posts = []
   for arg in args
     posts << Post.find(arg)
   end
   posts
end

Obviously the above is inefficient as you are making many SQL calls. If you want it efficient then you can write a code that makes one sql call (but will not return duplicates) and then iterate through the array and rearrange (with copying for duplicates) such as (not fully tested):

def find_with_array(*args)
  posts_with_no_duplicates = Post.find(args)
  posts_with_duplicates = []
  for arg in args
    for post in posts_with_no_duplicates
       if arg == post.id
         posts_with_duplicates << post
       end
    end
  end
end

This one should be better as you are only making one call to DB (normally slowest part) however it's O(N^2) There might be a way to make it O(N) if need be. However It's great improvement from the previous option

Upvotes: 1

Robert
Robert

Reputation: 985

Without knowing more detail, here's what I would advise. Take a look at this post regarding checkbox arrays: http://www.skuunk.com/2008/05/checkbox-arrays-in-rails.html

Each checkbox drops a value into a particular params key. This will solve the problem of getting an array with a list of values. Let me know in the comments if this doesn't resolve your particular issue.

Upvotes: 0

Related Questions