checking arrays if exist efficiently

29 views
Skip to first unread message

Soichi Ishida

unread,
Jun 12, 2013, 1:38:16 AM6/12/13
to rubyonra...@googlegroups.com
Rails 4.0.0

I am developing an app that checkes information updates automatically.
When the checking algorithms get to work, they receive an array of
contents such as

info_obtained: ['Tom', 'Steven', 'Bill', ...]

then, the app needs to check if each element of the array is already
persisted in the database.

Of course, I can loop through all elements like

Info.all.each do | i |
if i == ... then
Info.create(... => i)
end
end

But it seems inefficient.

Is there better ways or gems that do the job I am looking for?

soichi

--
Posted via http://www.ruby-forum.com/.

jainvi...@gmail.com

unread,
Jun 12, 2013, 1:44:22 AM6/12/13
to rubyonra...@googlegroups.com
Please, You not fetch all rows from database table. For better way is, you can fetch data with filter using 'where' cluase and Proceed on data.

Pry Flack

unread,
Jun 12, 2013, 12:11:36 PM6/12/13
to rubyonra...@googlegroups.com
Soichi Ishida wrote in post #1112146:
> Rails 4.0.0
> Of course, I can loop through all elements like
>
> Info.all.each do | i |
> if i == ... then
> Info.create(... => i)
> end
> end
>
> But it seems inefficient.
>
> Is there better ways or gems that do the job I am looking for?
>
> soichi

Not sure I understand fully your problem.

Maybe use find_in_batches ?
http://api.rubyonrails.org/classes/ActiveRecord/Batches.html

or find_and_create_by_column_name ?
http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Tamara Temple

unread,
Jun 12, 2013, 11:35:57 PM6/12/13
to rubyonra...@googlegroups.com
It's also not clear to me what you're doing with the items. From your
snippet of pseudocode, you want to *create* a *new* item with the
matching item when you find a match??

Soichi Ishida

unread,
Jun 12, 2013, 11:45:02 PM6/12/13
to rubyonra...@googlegroups.com
Sorry about my poor coding and language skills. I appreciate your
comments.

> Maybe use find_in_batches ?

> or find_and_create_by_column_name ?

will probably help. I'll take a look.

thanks
Reply all
Reply to author
Forward
0 new messages