修改参数键以在控制器中使用查询两次



我正在使用Ransack在我的应用程序上运行搜索。我有一个用户输入文本的搜索栏,文本被传递到搜索控制器,我在两个表中搜索查询:帖子和组

问题是我想分别对组和帖子的:name:title运行查询,然后在同一页面上提供两组结果。搜索表单使用 :name_cont,因此当我对帖子运行相同的搜索时,我正在尝试复制此表单发送到控制器的哈希值并将键更改为 :title_cont。

不要犹豫,要求澄清。

搜索控制器

class SearchController < ApplicationController
def index
@q = Group.search(params[:q])
@groups = @q.result
@group_count = @groups.count
#query = params[:q][:name_cont]
posthash = { :q => {:title_cont => params[:q][:name_cont]} }
@q = Post.search(posthash)
@posts_results = @q.result(:distinct => true)
@post_count = @posts.count
end
end

搜索表格:

=search_form_for @q, :url => { :controller => "search", :action => "index" }do |f|
=f.text_field :name_cont
=f.submit 'search'

它产生的错误:

undefined method `name_cont' for #<Ransack::Search:0x007fc0f798df18>

更新 1:

class SearchController < ApplicationController
def index
@q = Group.search(params[:q])
@groups = @q.result
@group_count = @groups.count
#I am trying to take the query, i.e. the "value" in params[:q]
#and pass it into a new hash to use as a parameter in 'search'
posthash = { :q => {:title_cont => params[:q][:name_cont]} }
@q2 = Post.search(posthash)
@posts_results = @q2.result(:distinct => true)
@post_count = @posts.count
end
end

您正在覆盖搜索帖子的@q,该帖子响应标题而不是名称,最终搜索表单会获得一个没有name_conttitle_cont的对象,因此您需要使用另一个变量名称来搜索@q以外的帖子。

最新更新