lost9123193
lost9123193

Reputation: 11030

Join two tables together in Ruby/Rails active record

I'm new to Rails and I'm not sure how to do this:

I'm writing a rake script that needs to reference off of a value from two tables: The owner_id in the Animals table references the Owner table:

Animals:[
 {id:1, name:"Bow wow", owner_id:1, score:null}, 
 {id:2, name:"Chiaow", owner_id:2, score:null}, 
 {id:3, name:"Fishbob and Ben", owner_id:9, score:null}
]

Owner:[
  {id:1, name:"Doug"}, 
  {id:2, name:"Michelle"}, 
  {id:9, name:"Ben"}
]

I would like to combine both these tables to get a result that looks like this:

Combined = [
  {id:1, score:null, keywords:"Bow Wow Doug", name:"Bow wow", owner:"Doug"}, 
  {id:2, score:null, keywords:"Chiaow Michelle", name:"Chiaow, owner:Michelle",
  {id:3, score:null, keywords:"Fishbob and Ben", name:"Fishbob", owner:"Ben"}
]

I want to also index through the keywords using

  combined_list = Combined.where("keywords LIKE (?)", "%#{chosen_word}%")

Is this possible?

Upvotes: 1

Views: 99

Answers (1)

eikes
eikes

Reputation: 5061

If you join two models (Animal and Owner) you can select which attributes from the joined table you want to make available in the instances:

combined = Animal.joins(:owner).select(:id, :name, 'owners.name as owner_name')
puts combined.first.name, combined.first.owner_name

This implies of course, that the Animal model belongs_to :owner.

To filter this relation I would do this:

cw = "%#{chosen_word}%"
combined.where('animals.name LIKE ?', cw).
         or(combined.where('owners.name LIKE ?', cw))

Upvotes: 1

Related Questions