前提・実現したいこと
親子関係のあるモデルの検索機能
Productモデル(親)で検索機能を作ったのですが検索をかけられるのがProdcutのカラムのみです。
そこで子の情報も検索したいと思っているのですがどうしていいかわかりません。
該当のソースコード
Productモデル 親 tagモデル has_many :tags accepts_nested_attributes_for :tags, allow_destroy: true categoryモデル has_many :product_categories
###カラム情報
create_table "tags", force: :cascade do |t| t.integer "product_id" t.string "tag_name" end create_table "categories", force: :cascade do |t| t.integer "product_id" t.string "category_name" end create_table "product_categories", force: :cascade do |t| t.integer "category_id" t.integer "product_id" end
試したこと
product.rb def self.search(search) if search Product.where(['price LIKE ?', "%#{search}%"]).or Product.where(['title LIKE ?', "%#{search}%"]).or Product.where(['id LIKE ?', "%#{search}%"]) else Product.all end end
###よろしくおねがします。記事だけの情報でも助かります。
###新しく作ったコード
def self.search(search) relation = Product.joins(:tags) relation .merge(Tag.where(['tag_name LIKE ?', "%#{search}%"])) .or(relation.where(['price LIKE ?', "%#{search}%"])).or(relation.where(['title LIKE ?', "%#{search}%"])).or(relation.where(['product_detail LIKE ?', "%#{search}%"])).uniq else Product.all end end end
このようなものを作ったのですがなぜか'kaminari'が不具合を起こして
ActionView::Template::Error (undefined method `total_pages' for #Array:0x0f105964):
このようなエラーを出します。
アドバイスお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/03/23 11:53
2018/03/23 12:10
退会済みユーザー
2018/03/23 13:45