0
我正在做一個內部連接(至少我認爲這就是代碼的工作),但我的搜索多次返回相同的結果。我想我的加入有問題。Rails搜索返回重複
標籤
+------------+--------------+------+-----+---------+----------------+
| 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
驚人......我放置之前不同而沒有得到地方。你是最好的。 :d – trowse