简体   繁体   中英

When thinking-sphinx finds data how do you then pull data out of the hash in ruby on rails?

Started using thinking sphinx today and I'd like to know what's going wrong here:

Here is my controller:

class SearchesController < ApplicationController
   def index
     @user = User.search params[:search]
   end
end

view:

<%= form_tag searches_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>


<%= @user %>

user model

  # thinking sphinx
  define_index do
    indexes username
    indexes email
  end

browser:

[#<User id: 35, email: "elna@hodkiewicz.net", encrypted_password: "$2a$10$4TCbzA3FLel4uZIAyILHVOFPNqyqShDEMPpv0FHsS24I...", password_salt: "$2a$10$4TCbzA3FLel4uZIAyILHVO", username: "yasmin35", created_at: "2012-01-24 10:01:38", updated_at: "2012-01-24 10:01:38", password_reset_token: nil, password_reset_sent_at: nil, email_change_token: nil, email_change_sent_at: nil>] 

I assumed because it found the user I could pull what ever info I wanted from that hash, so I tried this just as a test:

<%= @user.username %>

and got this:

undefined method `username' for #<ThinkingSphinx::Search:0x0000010497e258>

I'm certain I expecting thinking sphinx to work the same way my rails find methods do but I guess they don't. How would I achieve what I'm trying to achieve?

I would like to find a user by username or email which is working..but once I'v got that info ..use it to access associations such as the users profile and photos... so basically just use sphinx find the user then do things the way I would without sphinx..

I'm wondering is there any point using sphinx to allow my users to search for another user by email or username..? country etc..

A user has one profile and many photos. I thought by finding the user first I could then take advantage of their associations without sphinx but I was wrong.

Someone please enlighten be. I'd really appreciate it.

Kind regards

ThinkingSphinx returns an array of results by default, which is why that User object is wrapped in [ ] square brackets.

This is the same way that a User.where(:something => true) statement works in Rails in that you need to call .first on the search or iterate over the results. Otherwise, you are calling .username on an array object which won't work.

In this case, you should be iterating over the result set:

class SearchesController < ApplicationController
   def index
     # plural since we could get multiple users returned
     @users = User.search params[:search]
   end
end

and your view would be

<% @users.each do |u| %>
  <%= u.username %>
<% end %>

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