简体   繁体   中英

Rails Thinking Sphinx:- How to select only some fields in the result and multiple tables select(association)

I am a rookie in Thinking Sphinx for Rails.

When Sphinx found a record, it will give all the fields in the table. How can i select only the needed fields?

And in my case, i also need reference to another table. how can i do that?

Thanks

This is an old thread, but as I found it whilst looking for the same information, I thought I'd share my answer.

It's not (as far as I can tell) clearly defined on the Thinking Sphinx homepage, but the search function on a model accepts the option :select - and in answer to your second question, it also accepts :joins , so if you had two related models:

class Project < ActiveRecord::Base
  attr_accessible :name
  has_many :tasks
end

class Task < ActiveRecord::Base
  attr_accessible :name
  belongs_to :project
end

You should be able to search your tasks like so:

Task.search "Fix Bug", 
            :select => 'tasks.id, tasks.name, projects.name as project_name', 
            :joins => [:project]

There's no doubt a slightly cleaner way to do this, so I'm happy to be corrected - the general idea works though!

EDIT (for thinking sphinx v3)

:select is used as a sphinx parameter in version 3, and instead you should add :select and :joins to a :sql hash. Otherwise you get some really strange errors that aren't that obvious!

The above example then becomes:

Task.search "Fix Bug", 
            :sql => { :select => 'tasks.id, tasks.name, projects.name as project_name', 
                      :joins => [:project] }

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