繁体   English   中英

在 Ruby/Rails 活动记录中将两个表连接在一起

[英]Join two tables together in Ruby/Rails active record

我是 Rails 的新手,不知道该怎么做:

我正在编写一个需要从两个表中引用一个值的 rake 脚本:Animals 表中的 owner_id 引用了 Owner 表:

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"}
]

我想将这两个表结合起来得到如下所示的结果:

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"}
]

我还想通过关键字索引使用

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

这可能吗?

如果您连接两个模型(Animal 和 Owner),您可以从连接表中选择要在实例中使用的属性:

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

这当然意味着 Animal 模型belongs_to :owner

为了过滤这种关系,我会这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM