Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you join another table that isn't an association in ARel?

I've got some SQL that's working when I want to look for particular pages that have the particular schemes assigned to it (all through the scheme_assignment):

Page.find_by_sql("
    SELECT pages.id
    FROM pages
    INNER JOIN scheme_assignments ON (scheme_assignments.schemable_type = 'Page' AND
                                      scheme_assignments.schemable_id = pages.sid)
    INNER JOIN schemes ON (schemes.sid = scheme_assignments.scheme_id AND
                           schemes.sid IN (4,6,7))
    GROUP BY pages.id")

When I tried to convert this to ARel:

Page.select("pages.id")
    .joins("scheme_assignments")
    .on("scheme_assignments.schemable_type = 'Page' AND scheme_assignments.schemable_id = pages.sid")
    .joins("schemes")
    .on("schemes.sid = scheme_assignments.scheme_id AND schemes.sid IN (1)")
    .group("pages.id")

I would get this error: NoMethodError: undefined methodjoin_sql' for "schemes":String`

How come? Is it because it's not an association in my Page model? Could one go about converting that SQL to ARel without creating the associations in the model?

like image 297
Ramon Tayag Avatar asked Dec 21 '22 10:12

Ramon Tayag


2 Answers

Page.joins("INNER JOIN scheme_assignments 
        ON (scheme_assignments.schemable_type = 'Page' AND scheme_assignments.schemable_id = pages.sid) 
        INNER JOIN schemes 
        ON (schemes.sid = scheme_assignments.scheme_id AND schemes.sid IN (4,6,7))").
    select("DISTINCT pages.*");
like image 134
rubish Avatar answered Jan 30 '23 14:01

rubish


Rails Guides

When you have an association set up, Rails knows what kind of join to use. I think (haven't tried it though) it should work this way:

Page.select("pages.id").joins("INNER JOIN scheme_assignments ON (scheme_assignments.schemable_type = 'Page' AND scheme_assignments.schemable_id = pages.sid)")...
like image 42
bassneck Avatar answered Jan 30 '23 13:01

bassneck