How Do I Scope Enums in Rails Using Sunspot?

拥有回忆 提交于 2019-12-06 14:07:04

I finally got this one solved. The issue was that although Rails stores the enum value as an integer in the database, it does not retrieve that integer when you call the enum attribute (in this case @upload.perspective). This returns a string corresponding to the name of the value instead ("front", "side", etc. in this case). The problem with this is that in my searchable block I was declaring the perspective field as an integer.

The solution:

A method in the model which grabs the enum id integer rather than the name:

def perspective_id
  Upload.perspectives[self.perspective]
end

Modifying the searchable block:

searchable do
  text :tag_list
  boolean :approved
  integer :perspective_id
  time :created_at
end

And the search block in the controller:

def index
  #if no perspective, set to empty hash so solr skips
  params[:perspective] ||= []
  @search = Upload.search do
    with :approved, true
    with :perspective_id, params[:perspective]
    fulltext params[:tag]
    fulltext params[:search] do
      minimum_match 1
    end
    paginate page: params[:page], per_page: 30
  end
    @uploads = @search.results
    @query = params[:search]
end

Rails enums are quite a dark magic. Remember it's all integers in the database.

I'm betting your params[:perspective] is a string(like 'front') and not an underlying integer. Calling Model.perspectives[:front] on the other hand will return proper integer value. Try converting it to underlying value using

Model.perspectives[params[:perspective]]

before passing to search method.

More info here: rails docs

You don't have to write those extra coding actually. Just do it like this:

searchable do
  #...
  string :perspective
  #...
end

#while searching
with :perspective, 'above'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!