Rails query join association table with alias

后端 未结 1 828
故里飘歌
故里飘歌 2021-02-18 15:47

I have a model Edge that belongs to the other model Node twice through different foreign keys:

def Edge < ActiveRecord::Base
    bel         


        
1条回答
  •  渐次进展
    2021-02-18 16:19

    As for Rails 4.2.1, I believe you just cannot provide an alias when using joins from ActiveRecord.

    If you want to query edges by the first node, you could do it just like you stated:

    Edge.joins(:first).where(nodes: {value: 1})
    SELECT "edges".* FROM "edges" INNER JOIN "nodes" ON "nodes"."id" = "edges"."first_id" WHERE "nodes"."value" = 1
    

    But if you have to query using both nodes, you can still use joins like this:

    Edge.joins(:first, :second).where(nodes: {value: 1}, seconds_edges: {value: 2})
    SELECT "edges".* FROM "edges" INNER JOIN "nodes" ON "nodes"."id" = "edges"."first_id" INNER JOIN "nodes" "seconds_edges" ON "seconds_edges"."id" = "edges"."second_id" WHERE "nodes"."value" = 1 AND "seconds_edges"."value" = 2
    

    0 讨论(0)
提交回复
热议问题