我想在两个表中搜索查询(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
我怎么能再加一张桌子?
最佳答案
还应指定第二个名称表:
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
关于mysql - 在两个表中搜索查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32743125/