我是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}%")
这可能吗?
如果要联接两个模型(动物模型和所有者模型),则可以从联接表中选择要在实例中使用的属性:
combined = Animal.joins(:owner).select(:id, :name, 'owners.name as owner_name')
puts combined.first.name, combined.first.owner_name
当然,这暗示着动物模型belongs_to :owner
。
要过滤此关系,我可以这样做:
cw = "%#{chosen_word}%"
combined.where('animals.name LIKE ?', cw).
or(combined.where('owners.name LIKE ?', cw))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句