views:

30

answers:

1

I can't understand why this code works:

@ads = Ads.find(
   :all,
   :joins => "INNER JOIN ad_users u ON u.ad_users_id=ads.ad_users_id"
 )

and this one doesn't:

    @ads = Ads.find(
   :all,
   :joins => :AdUsers
 )

my classes are:

class Ads < ActiveRecord::Base
  set_primary_key :ads_id
  belongs_to :AdUsers
end

and

class AdUsers < ActiveRecord::Base
  set_primary_key :ad_users_id  
  has_many :Ads
end

I use a sqlite database. The sql generated for the join is:

SELECT "ads".* FROM "ads" INNER JOIN "ad_users" ON "ad_users"."ad_users_id" IS NUL

can anyone help me? I know this is not a blocker, but I don't want to write the join SQL if I don't have to.

thanks

+1  A: 

Without digging in too deeply, I see a couple things that could be confusing the join logic. First, I think you want your symbols to be lower cased with underscores on the joins clause and the associations. (Eg, :ad_users instead of :AdUsers) Also, the Rails conventions suggest singular classnames, though if you really want to you can get around this by specifying the class name explicitly:

class AdUsers < ActiveRecord::Base
  set_primary_key :ad_users_id
  has_many :ads, :class_name => 'Ads'
end
# ...and so forth

Unless you have a good reason, though, I'd suggest just using singular class names.

John Hyland
it says: Association named 'ad_users' was not found; perhaps you misspelled it?
tiagodll
I don't get any errors with :AdUsers, just doesn't return any row..
tiagodll
just saw, the sql generated is: SELECT "ads".* FROM "ads" INNER JOIN "ad_users" ON "ad_users"."ad_users_id" IS NUL
tiagodll
Did you change both the joins clause and the associations?
John Hyland
no, I am running the same code I posted before
tiagodll
The Rails conventions suggest singular class names (I just noticed yours are plural), and specifying associations in lowercase with underscores. I haven't built a sandbox app to test anything out, but my guess is that your plural class names and camel-cased associations are confusing the join logic.
John Hyland
If you really don't want to change the class names, you might also try specifying the class name in the association. (eg, has_many :ads, :class_name => 'Ads')
John Hyland
It works now, thank you!
tiagodll