【发布时间】:2016-01-14 18:31:30
【问题描述】:
这是我的控制器索引中的代码。对于@posts,我只显示已发布的帖子和用户不喜欢的帖子、rsvp 等。当我添加对 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
【问题讨论】:
标签: ruby-on-rails elasticsearch scope searchkick