我正在进行内连接(至少我认为这是代码正在做的事情)但我的搜索多次返回相同的结果。我想我的加入有问题。
标签
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| color | varchar(255) | YES | | NULL | |
| article_id | int(11) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
文章
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(255) | YES | | NULL | |
| info | text | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
我标记的每篇文章都会根据标记返回多个结果。因此,如果文章有3个标签,则会返回3条记录。即使每篇文章只返回1个?
class Article < ApplicationRecord
has_many :tags, dependent: :destroy
validates :title, presence: true
def self.search(search)
if search
joins(:tags).where('title LIKE :search OR tags.name LIKE :search', search: "%#{search}%")
else
all
end
end
end
答案 0 :(得分:1)
使用.distinct或.group。从rails 4.0.2开始也有.uniq别名。
示例:
joins(:tags).where('title LIKE :search OR tags.name LIKE :search', search: "%#{search}%").distinct
joins(:tags).where('title LIKE :search OR tags.name LIKE :search', search: "%#{search}%").
group('article_id')