I
I
Ilya Lozer2014-04-17 16:30:47
Ruby on Rails
Ilya Lozer, 2014-04-17 16:30:47

Ruby On Rails - how to refactor (Ruby array)?

1.)tournament = Tournament.where("date = ?", date)"
2.)arr = []
3.)tournament.map do |x|
4.) arr += [x.id] if x.tournament_locales .where(:locale=>"en").count > 0
5.)end
6.)return arr
Lines 2-6. I often have to do this, I especially don't like this explicit declaration of a variable. crutch solution?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
@
@mgyk, 2014-04-17
@ammet

tournament.select{|x| x.tournament_locales.where(:locale => "ru").count > 0 }

Although in this example it is much better to do this on the DB side.

B
Boris Penkovsky, 2014-04-17
@Able1991

Yuzai DataMapper

arr = Tournament.all(:conditions => {Tournament.date => date, Tournament.tournament_locales.locale => 'ru'})

K
Kirill Platonov, 2014-04-17
@kirillplatonov

results = Tournament.select("tournaments.id, (select count(*) from tournament_locales where locale = 'ru') locales_count").joins(:tournament_locales).where("date = ? AND locales_count > 0", date).pluck('tournaments.id')
results

I could make a mistake somewhere in the code, there will be errors - throw it, we'll fix it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question