0

我已经实现了一些基本搜索,我正在尝试将多个属性与一组关键字匹配。

我有这个:

listings = Listing.order(:headline)
listings = listings.where("headline like ?", "%#{keywords}%") if keywords.present?

我有多个属性listings,我想检查它是否keywords出现在 - 例如说listing.neighborhood.namelisting.type.name

我如何在 1 条语句中写下所有这些内容?我试过:

listings = listings.where("headline like ? or neighborhood.name like ?", "%#{keywords}%")

但这返回了这个错误:

ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 2) in: headline like ? or neighborhood.name like ?

一个明显的解决方案是"%#{keywords}%"再次添加......但这似乎并不干燥。

如何在该 1 查询中添加检查和其他neighborhood.nametype.name或者我应该以另一种方式接近这个?

谢谢。

编辑1:

当我尝试简单地添加另一个参数的非 DRY 方式时{keywords},这是我得到的错误:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: neighborhood.name: SELECT "listings".* FROM "listings"  WHERE (headline like '%sterling place%') AND (headline like '%sterling place%' or neighborhood.name like '%sterling place%') ORDER BY headline.

我认为这是因为neighborhood是我模型上的 foreign_key listings,而不是其本身的属性。listings&neighborhood模型之间有一个简单的关联。

4

3 回答 3

2

试试这个(仍然是一种非干燥的方式):

key = "%#{keywords}%"
listings = Listing.includes(:neighborhood).where("headline like ? or neighborhoods.name like ?", key, key)
于 2013-02-11T12:51:17.067 回答
2

我认为您没有很多选择可以使其干燥...但是您可以执行以下操作:

listings = listings.where("headline like :keywords or neighborhood.name like :keywords", :keywords => "%#{keywords}%")

编辑:我没有意识到这种关联...... siekfried是对的......如果你开始添加更多列,那就再干一点:

listings = Listing.includes(:neighborhood).where("listings.headline like :keywords or neighborhoods.name like :keywords", :keywords => "%#{keywords}%")
于 2013-02-11T13:10:41.237 回答
1

尝试:

listings = listings.where("headline like ? or neighborhood.name like ?", "%#{keywords}%", "%#{keywords}%")
于 2013-02-11T12:56:59.250 回答