Question

I am working on a Ruby on Rails application which already has logic for text searching using pg_search and two other fields on a model. The logic creates an 'array' of rows from the search result. I do not remember the actual name of this since technically this is not an array. It is an instance variable of selected rows. I want to add search criteria from two additional models. My database is PostgreSQL.

Here is a subset of all three model definitions:

MediaLibrary: name, media_creator_id, media_type_id (fields that are being used in current search; has many media_topics and has many media_targets)

MediaTopic: media_library_id, topic_id (want to search for topic_id; belongs to media_library; topic_id being searched is coming from a Topic model (id, name))

MediaTarget: media_library_id, target_id (want to search for target_id; belongs to media_library; target_id being searched is coming from a Target model (id, name))

I'm thinking that I should be able to do something like this if both topic and target are being searched along with the other three search criteria. I will also need to have topic_id and target_id in my results so I can display Topic.name and Target.name on my view.

@media_libraries = MediaLibrary.text_search(params[:query]).where("media_creator_id = ? AND media_type_id = ?", params[:media_creator_id].to_i, params[:media_type_id].to_i).joins(:media_topics.where("media_library_id = ? and topic_id = ?", id_from_media_library_row, params[:topic_id].to_i).joins(:media_targets.where("media_library_id = ? and target_id = ?", id_from_media_library_row, params[:target_id].to_i)

I have searched on postgresql.org and Stack Overflow but have not found anything joining three tables using Ruby on Rails that was answered by anyone.

Was it helpful?

Solution

You can pass a SQL join statement into #joins. I'm not sure what it'd be in your case but you can do something like:

@media_libraries = MediaLibrary.joins(%q(
  JOIN media_targets
    ON media_targets.media_library_id = media_libraries.id
  JOIN media_topics
    ON media_topics.media_library_id = media_libraries.id
)).text_search(params[:query])
  .where(
    media_libraries: {
      media_creator_id: params[:media_creator_id],
      media_type_id: params[:media_type_id]
    },
    media_topics: { id: params[:topic_id] },
  )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top