开发者

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?


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.*");


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)")...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜