Saturday 15 February 2014

ruby on rails - ActiveRecord find with include against table with records that might not be there -



ruby on rails - ActiveRecord find with include against table with records that might not be there -

here's situation. have set of lists of words. words can appear in more 1 list. each word/list combination, might have illustration sentence.

words

class word < activerecord::base has_and_belongs_to_many :lists has_many :sample_sentences end

lists

class list < activerecord::base has_and_belongs_to_many :words has_many :sample_sentences end

sample sentences

class samplesentence < activerecord::base belongs_to :word belongs_to :list end

... , back upwards habtm, have bring together table.

everything works fine except this:

using eager loading, grab words in particular list and sample sentences word particular list.

i have tried many variations scopes, wheres, etc.

most variations (testing in irb)

w=word.includes(:sample_sentences).where(words: {id: 48}).where(sample_sentences: {list_id: 6})[0]

this works great if word has illustration sentence in associated list. does not work if word has no illustration sentence in list. returns no records.

the documentation active record query interface , countless questions on stack overflow tell me resulting sql uses left outer bring together data. believe issue result of additional on sample_sentences table seems eliminate possibility of getting word query no sample sentences.

this indeed borne out.. if drop additional on sample_sentences table, records regardless of whether or not word has associated sample sentence. problem is, sample sentences in not interested.

development database engine sql lite. production mysql.

so.. i'm not sure best thing be. thoughts?

if reading request correctly using eager loading, grab words in particular list , sample sentences word particular list.. appears want words regardless of whether have comments. seek this: word.includes(:sample_sentences, :lists).where(lists: {id: #list id }). include sample sentences if exist , can test empty?.

ruby-on-rails ruby activerecord eager-loading

No comments:

Post a Comment