gpt4 book ai didi

ruby-on-rails - 如何在 Controller 中的searchkick中使用作用域?

转载 作者:行者123 更新时间:2023-12-02 22:17:00 25 4
gpt4 key购买 nike

这是我的 Controller 索引中的代码。对于@posts,我只显示已发布的帖子和用户不喜欢的帖子,rsvp等。当我添加对searchkick的搜索时,它将忽略其他条件。搜索有效,但其中包含未发布的帖子等。如何在模型或 Controller 中进行调整以能够搜索和限制我的查询。

@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

最佳答案

// query =搜索查询字词

// @ rsvps,@ favorites,@ unshows => 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}
}

关于ruby-on-rails - 如何在 Controller 中的searchkick中使用作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34797144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com