rails : how can I use find_each with map?


I have a form that has nested field (habtm and accepts_nested_attributes_for). That form contains with a field "keywords", that autocompletes keywords that come from a postgresql table.

All that works well. This is in params :

"acte"=>{"biblio_id"=>"1",  "keywords"=>{"keywords"=>"judge, ordeal, "}

What I now need to do is take those keywords and get their keywords_id out of the table keywords. Those id must be added to the join table.

I'm doing this :

q = params[:acte][:keywords].fetch(:keywords).split(",")
a = q.map {|e| Keyword.find_by keyword: e } 

As per the guides, find_by returns only the first matching field. I guess I would need to use find_each but I'm not certain about that and I can't get it to word. I have tried this:

q = params[:acte][:motclefs].fetch(:motclefs).split(",")
a = Array.new
Motclef.where(motcle: q).find_each do |mot|
  a << mot.id

This also finds only the first result like : [251].

What I'm looking to get is something like [1453, 252, 654]

thanks !

Show source
| find   | postgresql   | ruby-on-rails   | each   2017-01-02 00:01 1 Answers

Answers to rails : how can I use find_each with map? ( 1 )

  1. 2017-01-02 00:01

    Putting find_by in a loop means you will be executing a separate SQL query for each SQL keyword.

    You can instead just get all the ids in a single SQL call by doing keyword in.

    After you do q = params[:acte][:keywords].fetch(:keywords).split(","), your q will be an array of keywords. So q will be ["judge", " ordeal"].

    You can simply do Keyword.where(keyword: q).select(:id) which will generate a query like SELECT keywords.id FROM keywords where keyword in ('judge', 'ordeal').

Leave a reply to - rails : how can I use find_each with map?

◀ Go back