views:

205

answers:

2

Hi,

I know a very, very similar question has been asked before. The hackish solution to that question doesn't work if I want to chain in more scopes, so I'm asking again here, with a bit more information as to where the issue is coming from.

# Relevant code only...
class Publication < ActiveRecord::Base
  has_many :issues
  has_many :articles, :through => :issues
end

class Issue < ActiveRecord::Base
  belongs_to :publication
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :issue
  define_index do
    has issue(:publication_id), :as => :publication_id
  end
end

Therefore, I'd expect the following code to work:

Publication.first.articles.search 'foobar'

However, it returns the following error:

RuntimeError: Missing Attribute for Foreign Key publication_id
    from /home/matchu/rails/torch/vendor/plugins/thinking-sphinx/lib/thinking_sphinx/active_record/has_many_association.rb:18:in `search'

This seems to imply that the publication_id attribute that I specifically set does not exist. However, it does.

Article.search :with => {:publication_id => 1}

So, I suppose I can just use that syntax, even though it's significantly less pretty. Making this question not particularly urgent. But I definitely am curious as to why this occurs. Any thoughts?

A: 

You didn't show what is in your Publication model, but can you even call Publication.first.articles? Thinking sphinx can't do anything with relationships unless you define them first in active_record:

# in Publication.rb
has_many :articles, :through => :issues

Searching directly on Article works, but only because you are making sphinx index the issue's publication_id, it doesn't create any relationships in active record.

Zef
Oh, I knew I failed somewhere. I was tired and put the Publication model's code into Issue. Now it all looks like nonsense. I'll have it edited in a minute.
Matchu
Edits have been made. Now it's not total nonsense anymore :)
Matchu
+1  A: 

Hi Matchu

I'm fairly certain (without getting stuck into the code - it's late where I am at the moment) that you're right, it should work how you have it set up. I assume it's an issue with assumptions on has_many, and not expecting a has_many :through.

If you could create an issue on GitHub, that'll help remind me to investigate further.

Cheers

pat
To future readers: Pat fixed the issue, and thus solved the problem. Thanks!
Matchu