rails连接两个表

时间:2014-04-05 18:28:13

标签: sql ruby-on-rails

模特:

Fruit:  fields - "fruit_type"  

has_many: apples
has_many :bananas  



Apple fields: f1, f2, fruit_id, some other fields  
belongs_to: fruit

Banana: f1, f2, fruit_id, some other fields related to banana  
belongs_to :fruit

如何通过搜索fruit_type,f1,f2字段来获取所有水果。我们有3个输入:fruit_type,f1,f2所以如果我们只键入一个字段(比如f1),则只搜索f1字段。如果输入fruit_type,f1,f2输入,则将搜索两个字段f1,f2,最后返回水果。

让我们说输入f1或只输入f2,然后输入:

scope = Fruit.joins("left join apples on apples.fruit_id=fruits.id left join bananas on bananas.id=fruits.id where (apples.f1 like '#{f1_input_val}%' or bananas.f1 like '#{f1_input_val}%')")  

如果还输入了fruit_type,f1,f2输入,那么查询是什么?以下不起作用:

scope = Fruit.all #if no queries

scope = scope.where("fruit_type like ?", "#{fruit_type_input}%")  if fruit_type_input.present?  

scope = scope.joins("left join apples on apples.fruit_id=fruits.id left join bananas on bananas.id=fruits.id where (apples.f1 like '#{f1_input_val}%' or bananas.f1 like '#{f1_input_val}%')") if f1_input_val.present?  

scope = scope.joins("left join apples on apples.fruit_id=fruits.id left join bananas on bananas.id=fruits.id where (apples.f2 like '#{f2_input_val}%' or bananas.f2 like '#{f2_input_val}%')") if f2_input_val.present?

1 个答案:

答案 0 :(得分:0)

我认为您需要将joininingwhere条款分开。

scope = Fruit.all #if no queries

scope = scope.where("fruit_type like ?", "#{fruit_type_input}%")  if fruit_type_input.present?  

if f1_input_val.present? or f2_input_val.present?
  scope = scope.joins("left join apples on apples.fruit_id=fruits.id left join bananas on bananas.id=fruits.id")

  scope = scope.where("apples.f1 like '#{f1_input_val}%' or bananas.f1 like '#{f1_input_val}%')") if f1_input_val.present?  
  scope = scope.where("apples.f2 like '#{f2_input_val}%' or bananas.f2 like '#{f2_input_val}%')") if f2_input_val.present?
end
scope # just return a resulted scope