如何在控制器中使用带有searchkick的范围?

时间:2016-01-14 18:31:31

标签: ruby-on-rails elasticsearch scope searchkick

这是我的控制器索引中的代码。对于@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

1 个答案:

答案 0 :(得分:3)

// query =搜索查询字词

// @rsvps,@ favorites,@ unshows =&gt; post_ids数组

Post.search query, 
          where: {
             published_at: {lte: Time.now.in_time_zone("Eastern Time (US & Canada)")},
             id: {not: @favorites},
             id: {not: @rsvps},
             id: {not: @unshows}
          }