在两个表中搜索查询

时间:2015-09-23 15:04:35

标签: mysql ruby-on-rails ruby ruby-on-rails-4

我想在两个表中搜索查询(users.name,users.email,object.name) 当我输入:

 def self.search(query)
    query = "%#{query}%"
    where("(name like ? or email like ?  or surname like ?)", query, query, query)
  end

它工作得很好,但现在我想添加下一个字段来搜索其他表格

def self.search(query)
        query = "%#{query}%"
        joins(:object).where("(objects.name like ? or name like ? or email like ?  or surname like ?)", query, query, query, query)
      end

错误:

`User Load (0.2ms)  SELECT  `users`.* FROM `users`  WHERE `users`.`id` = 120  ORDER BY `users`.`id` ASC LIMIT 1
   (1.2ms)  SELECT COUNT(*) FROM `users` INNER JOIN `objects` ON `objects`.`id` = `users`.`object_id` WHERE ((objects.name like '%ver%' or email like '%ver%' or name like '%ver%' or surname like '%ver%'))
Mysql2::Error: Column 'name' in where clause is ambiguous: SELECT COUNT(*) FROM `users` INNER JOIN `objects` ON `objects`.`id` = `users`.`object_id` WHERE ((objects.name like '%ver%' or email like '%ver%' or name like '%ver%' or surname like '%ver%'))
Completed 500 Internal Server Error in 6ms
`

我的模特

User belongs_to :object
Object has_many :users

我如何添加其他表?

1 个答案:

答案 0 :(得分:2)

您还应指定第二个名称表:

def self.search(query)
  query = "%#{query}%"
  joins(:object).where("(objects.name like ? or users.name like ? or email like ?  or surname like ?)", query, query, query, query)
end