0
votes

I'm using sunpost gem for search in my rails project.

I have now two languages in my app:

I18n.default_locale = :en
LANGUAGES = [
['English',
'en'],
["Español".html_safe, 'es']
]

I have in my post.rb model, a language attribute that contains the value "es" for spanish language or value "en" for english language.

I have in posts_controller in index action the next method:

def index
   @search = Post.solr_search do |s|
     s.fulltext params[:search]
     s.keywords params[:search]
     s.order_by :created_at, :desc
     s.paginate :page => params[:page], :per_page => 20
   end

   @posts = @search.results

    respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @posts }
    format.js
  end 
 end

I get the current language with I18n.locale.to_s I get with this code "es" or "en"

My question is: How can I only show the results for the language currently in use by user in my website?

Thank you very much!

1

1 Answers

1
votes

It would be very helpful if you could post the searchable block in the post model. But until then, I will take a stab at it.

Your Post model should look something like the following:

class Post < ActiveRecord::Base
  searchable do
    ...
    string :language
    ...
  end
end

Where you are indexing the language the post is written/stored in.

Then your controller you use the language field as a filter. It should look like:

def index
  @search = Post.search do |s|
    s.keywords params[:search]
    s.with(:language, I18n.locale.to_s) if I18n.locale.present?
    s.order_by :created_at, :desc
    s.paginate :page => params[:page], :per_page => 20
  end

  @posts = @search.results

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @posts }
    format.js
  end 
end

and there you have it!