Has_many with :finder_sql doesn't actually give out data?

Hi,

I have a model unrelated to a table, and I want to assign three has_many
child relationships.

ie.,

has_many :classifieds, :conditions => %q/ email = '#{email}' /
#=> SELECT * FROM classifieds WHERE (classifieds.white_label_id = 

NULL
AND ( email = ‘[email protected]’ ))

But that assumes that I´ll find the name of the model as a foreign key
field
in the jobs table (which I won’t). I want to use the email as the
foriegn
key so I tried (setting model.email=email before calling for the
children)

attr_accessor :email

has_many :classifieds, :foreign_key => :email

And requesting with

model.classifieds.find :all

But the resulting SQL is

SELECT * FROM classifieds WHERE (classifieds.email = NULL)

So I try setting the email address as a condition

has_many :classifieds, :foreign_key => :email, :conditions => %q/ 

email
= ‘#{email}’ /
#=> SELECT * FROM classifieds WHERE (classifieds.email = NULL AND (
email = ‘[email protected]’ ))

Not much use there either. I tried setting foriegn_key to false and nil
and
nothing seemed to get rid of it from the query, and I can´t find any
documentation on getting rid of it, so I decided to try a different
approach: :finder_sql

has_many :classifieds, :finder_sql => %q/
    SELECT DISTINCT i.*
    FROM classifieds i
    WHERE i.email = '#{email}'
/

Which is interesting. Because now

model.classifieds #=> []
model.classifieds.count #=> 8
model.classifieds.find :all #=> nil
model.classifieds.find 38 #=> nil (where 38 is the id of an item 

that
exists)

Very long story short, the only way I can get all of my data out of
:finder_sql is to use .find_all email but since :find_all is deprecated,
I
don’t think that’s a good idea.

Please can someone point out to me where I’m going so far wrong with
this
approach?

Cheers,
Morgan G…

Morgan G. wrote:

Very long story short, the only way I can get all of my data out of
:finder_sql is to use .find_all email but since :find_all is deprecated, I
don’t think that’s a good idea.

find_all is deprecated because it was replaced with find(:all). But
that’s probably still not the best approach.

To be honest I’m having a bit of trouble figuring out exactly what
you’re trying to do, and how to go about it. If you could paste the
code for the models involved (not all of it, just enough to show the
relationships) and their migrations, maybe I or someone else can help
you out a bit more.

I’m also curious what the SQL calls look like that produces each of
the strange results (nil array, count of 8, etc.) you mention.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs