2
這是我的控制器索引中的代碼。對於@posts,我只顯示發佈的帖子和帖子,其中用戶不喜歡,rsvp等。當我添加searchkick搜索時,它忽略了其他條件。搜索工作,但它包括未發佈的帖子等。如何在模型或控制器中進行調整以便能夠搜索和限制我的查詢。如何在控制器中使用searchkick的範圍?
@favorites = current_user.favorites
@rsvps = current_user.rsvps
@unshows = current_user.unshows
query = params[:q].presence || "*"
@posts = Post.published.where.not(id: @unshows).where.not(id: @favorites).where.not(id: @rsvps).search(query)
這是我的模型。
class Post < ActiveRecord::Base
belongs_to :user
default_scope -> { order(created_at: :desc) }
searchkick text_start: [:title]
def search_data
{
title: title,
description: description,
location: location,
date: date
}
end
validates :user_id, presence: true
validates_presence_of :slug
has_many :repluggers, :class_name => 'user', :foreign_key => 'user_id'
has_many :replugs, :class_name => 'post', :foreign_key => 'replug_id'
has_attached_file :image, :styles => { :medium => "800x800#", :thumb => "100x100#" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
# Favorited by users
has_many :favorite_posts # just the 'relationships'
has_many :favorited_by, through: :favorite_posts, source: :user
# Favorited by users
has_many :rsvp_posts # just the 'relationships'
has_many :rsvp_by, through: :rsvp_posts, source: :user
# Favorited by users
has_many :unshow_posts # just the 'relationships'
has_many :unshow_by, through: :unshow_posts, source: :user
scope :draft, ->{where(published_at: nil)}
scope :published, ->{where.not(published_at: nil).where("published_at <= ?", Time.now.in_time_zone("Eastern Time (US & Canada)"))}
scope :scheduled, ->{where.not(published_at: nil).where("published_at >= ?", Time.now.in_time_zone("Eastern Time (US & Canada)"))}
attr_accessor :status
before_validation :clean_up_status
def clean_up_status
self.published_at = case status
when "Draft"
nil
when "Published"
Time.zone.now
else
published_at
end
true
end
def slug
title.to_s.downcase.strip.gsub(" ", "-").gsub(/[^\w-]/, '')
end
def to_param
"#{id}-#{slug}"
end
end