How to use Arel::Nodes::TableAlias in an initial where statement How to use Arel::Nodes::TableAlias in an initial where statement ruby ruby

How to use Arel::Nodes::TableAlias in an initial where statement


You might be able to use the attribute table_alias which you can call on an Arel::Table.

Example:

# worksusers = User.arel_tablesome_other_table = Post.arel_tableusers.table_alias = 'people'users.join(some_other_table)# doesn't workusers = User.arel_table.alias('people')some_other_table = Post.arel_tableusers.join(some_other_table)


the as method generate an arel object which doesn't has where method such Relation objectthe Arel object generates a sql to be executed basically its a select manageryou can use union and give it another condition then use to_sqlfor example:

arel_obj = current_node.children.as("children_nodes").Union(Node.where(....)

sql_string = arel_obj.to_sql

Node.find_by_sql(sql_string)

here is some links that might helphttp://www.rubydoc.info/github/rails/arel/Arel/SelectManager


In Arel, as will take everything up to that point and use it to create a named subquery that you can put into a FROM clause. For example, current_node.children.as("children_nodes").to_sql will print something like this:

(SELECT nodes.* FROM nodes WHERE nodes.parent_id = 5) AS children_nodes

But it sounds like what you really want is to give a SQL alias to the nodes table. Technically you can do that with from:

current_node.children.from("nodes AS children_nodes").to_sql

But if you do that, lots of other things are going to break, because the rest of the query is still trying to SELECT nodes.* and filter WHERE nodes.parent_id = 5.

So I think a better option is to avoid using an alias, or write your query with find_by_sql:

Node.find_by_sql <<-EOQ    SELECT n.*    FROM   nodes n    WHERE  n.parent_id = 5    AND EXISTS (SELECT 1                FROM   nodes n2                WHERE  ....)EOQ

Perhaps you could also make things work by aliasing the inner table instead:

current_node.children.where(  Node.from("nodes n").where("...").select("1").exists)