简体   繁体   中英

GEM Ransack - using ransack to search through a link - Rails 4

i'm new to rails so your help and advise would be much appreciated.

  • i am currently using the gem ransack
  • in my schema i have a table called adverts with the columns title & content
  • i am trying to create a search with ransack through a link
  • i have a link called similar jobs [ <%= link_to 'similar jobs', search_adverts_path(q: {advert_title_eq: @advert.title}), class: "fa fa-plus-square" %> ]
  • currently in my app when a user clicks on similar jobs for an advert with the title risk analyst , it displays search results with the exact advert title 'risk analyst' but what i would like is to display search results containing 'risk' & 'analyst' - so example, 'business analyst' 'risk analyst' 'financial analyst' etc should be displayed in the search result list, but only 'risk analyst' is being displayed

what i want to do is:

  • when a user views an advert eg: risk analyst and clicks on the link 'similar jobs' the search should display adverts with titles containing 'risk' & 'analyst'

adverts_controller.rb

in my adverts controller i have the below action:

  def search
    @userj = current_userj
    if params[:q].present? and params[:q][:advert_title_eq].present?
     params[:q][:title_cont] = params[:q][:advert_title_eq]
    end 
    @search = Advert.search(params[:q])
    @adverts = @search.result(distinct: true)
    @active_adverts = @adverts.where(['appdeadline >= ?', Time.zone.today]) #displays adverts with deadline > or = to current date
    @active_adverts_count = @active_adverts.count
  end

views / adverts / show.html.erb

<%= link_to 'similar jobs', search_adverts_path(q: {advert_title_eq: @advert.title}), class: "fa fa-plus-square" %>

A github repo Ransack link search have the solution of similar problem.

where, the link is as:

<%= link_to 'similar jobs', search_adverts_path(q: {title_cont_any: @advert.title.split(' ')}) %>

and the search action is as:

def search @search = Advert.search(params[:q]) @adverts = @search.result(distinct: true) end

But, if you want to solve in your way, just refactor the search action if condition block only as

if params[:q].present? and params[:q][:advert_title_eq].present? params[:q][:title_cont_any] = params[:q][:advert_title_eq].split(' ') end

It can be done at link level:

<%= link_to 'similar jobs', search_adverts_path(q: {advert_title_cont_any: @advert.title.split}), class: "fa fa-plus-square" %>

I found at ransack wiki . I did test it at rails console.

Also, you'll need to remove:

if params[:q].present? and params[:q][:advert_title_eq].present?
  params[:q][:title_cont] = params[:q][:advert_title_eq]
end

At your controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM