我有一個Forum
即has_many
:forum_threads
和has_many :forum_posts, through: :forum_threads
。所以基本上我的論壇都有自己的論壇主題,這些論壇主題與特定的論壇主題相關。我添加了Searchkick來處理搜索表單。 Searchkick正在爲我的Forum
表工作,但不適用於我的ForumThread
表。Ruby on Rails 4:Searchkick顯示所有項目而不是搜索結果
沒有錯誤,它只是呈現出所有的論壇線程,而不是呈現給定表單的查詢。
這裏是我的文件:
forum.rb
class Forum < ActiveRecord::Base
accepts_nested_attributes_for :forum_threads
has_many :forum_posts, through: :forum_threads
accepts_nested_attributes_for :forum_posts
searchkick text_start: [:title], suggest: [:title], autocomplete: [:title]
def search_data
{
title: title
}
end
end
forums_controller.rb
class ForumsController < ApplicationController
def index
query = params[:q] || "*"
@forums = Forum.search(query, suggest: true, fields: [:title],
boost_where: {specific: :exact})
end
end
個視圖/論壇/ index.html.erb
<%= form_tag forums_path, method: :get do |f| %>
<%= text_field_tag :q, nil, class: 'form-control', placeholder: 'Search...' %>
<% end %>
<% if @forums.suggestions.any? %>
<p class="lead">
<em>Did you mean: <strong><%= @forums.suggestions.first %></strong>?</em>
</p>
<% end %>
forum_thread.rb
class ForumThread < ActiveRecord::Base
belongs_to :user, counter_cache: true
belongs_to :forum, counter_cache: true, touch: true
has_many :forum_posts, dependent: :destroy
accepts_nested_attributes_for :forum_posts
validates :subject, presence: true
validates_associated :forum_posts
searchkick text_start: [:subject], suggest: [:subject], autocomplete: [:subject]
def search_data
{
subject: subject,
description: description
}
end
end
forum_threads_controller.rb
class ForumsController < ApplicationController
def index
query = params[:q].presence || "*"
@forum_threads = @forum.forum_threads.search(query, suggest: true, fields: [:subject, :description])
end
end
視圖/ forum_threads/index.html中.erb
<%= form_tag forum_forum_threads_path(<!-- something here? -->), method: :get do %>
<%= text_field_tag :q, nil, class: 'form-control', placeholder: 'Search...' %>
<% end %>
<% if @forum_threads.suggestions.any? %>
<p class="lead"><em>Did you mean: <%= @forum_threads.suggestions.first %>?</em></p>
<% end %>
的routes.rb
Rails.application.routes.draw do
resources :forums do
resources :forum_threads do
resources :forum_posts do
member do
put 'like', to: 'forum_posts#upvote'
put 'dislike', to: 'forum_posts#downvote'
end
end
end
end
end