Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-pluginsthinking-sphinx

Thinking Sphinx and multiple has_one


I've got multiple has_one associations in my model

class Invoice < ActiveRecord::Base
...
belongs_to :seller, :class_name => "Client", :foreign_key => "provider", :conditions => ['is_provider = ?', true]
belongs_to :customer, :class_name => "Client", :foreign_key => "receiver", :conditions => ['is_receiver = ?', true]

I'm trying to index it:

indexes [seller(:tbClientCode), seller(:tbClientLabel), seller(:tbClientName), seller(:tbClientNIP), 
  seller(:tbClientRegon), seller(:tbClientZip), seller(:tbClientCity), seller(:tbClientStreet), 
  seller(:tbClientHouseNr), seller(:tbClientHomeNr], :sortable => true, :as => :seller_fields    
has  [seller(:is_provider), seller(:is_receiver)], :sortable => true, :as => :seller_attributes      

indexes [customer(:tbClientCode), customer(:tbClientLabel), customer(:tbClientName), customer(:tbClientNIP), 
  customer(:tbClientRegon), customer(:tbClientZip), customer(:tbClientCity), customer(:tbClientStreet), 
  customer(:tbClientHouseNr), customer(:tbClientHomeNr], :sortable => true), :as => :customer_fields    
has  [customer(:is_provider), customer(:is_receiver)], :sortable => true, :as => :customer_attributes

... and then some error occurs

ERROR: index 'invoice_core': sql_range_query: ERROR:  column reference "is_receiver" is ambiguous
LINE 1: ...tomers_invoices"."id" = "invoices"."receiver" AND is_receive...

Changing syntax from customer(:tbClientName) to customer.tbClientName is not solution.

Some help would be greatly appreciated


Solution

  • Well, firstly: I don't think you actually want to combine all those columns into just one field and just one attribute?

    So, remove the [] - you can pass in multiple columns, but if you pass in an explicit array, then that'll group those columns together into a single field/attribute. Thus, remove the :as option as well - you don't want all of those columns together having the same name, the generated SQL statement won't make any sense.

    Secondly: attributes are sortable by their very nature, so you don't need to pass :sortable => true to the has call. Also: do you really need all of the fields to be sortable? Better to only mark the fields that should be sortable as such.

    But lastly, and perhaps most importantly: the error that's actually happening is because of your conditions hash for your two associations. You're joining on the same table twice, but you don't have any table references in the conditions. Try changing both conditions settings to the following:

    :conditions => {:is_provider => true}
    :conditions => {:is_receiver => true}