Rails: collecting records from grandparent's attributes -
i've got deep-nested relationship so:
>> @document.template_variables.first.master.box.stack => #<stack id: 6, name: "contact information", direction: "down", x: 145.0, y: 145.0, template_id: 28, width: 55, page: 1, html_box: "column_right">
master isn't quite normal rails relationship, , it's defined in templatevariable
so:
def master templatevariable.find(master_id) if master_id.present? end
so it's kinda referring instance of itself, can see log output on top works fine.
my issue need all templatevariables
parent stack
matches box name so:
scope :by_box, -> (b) { where('box.stack.html_box' => b) }
but no matter try, in console, can't query right.
>> @document.template_variables.where(master.box.stack.html_box != nil) !! #<nameerror: undefined local variable or method `master' #<#<class:0x007fd287cd9888>:0x007fd28bb11ee8>>
and scope returns error:
activerecord::statementinvalid - pg::undefinedtable: error: missing from-clause entry table "box" line 1: ...where "template_variables"."document_id" = $1 , "box"."sta...
any help? missing?
i think should create answer here. scope raised error because did not joins table boxes
, stacks
before clause where('box.stack.html_box' => b)
. rails convert sql query
select "template_variables".* "template_variables" "box"."stack.html_box" = ...
as can see, query has no idea clause. "box"
table? "stack.html_box"
column? have join boxes
, stacks
first, clause where(stacks: { html_box: b })
or where('stacks.html_box' => b })
(stacks
plural because table name), convert sql query
select "template_variables".* "template_variables" inner join "boxes" on "boxes"."id" = "template_variables"."box_id" inner join "stacks" on "stacks"."id" = "boxes"."stack_id" "stacks"."html_box" = ...
and work well. suggestion, shoud define master
belongs_to
association, like
belongs_to :master, class_name: 'templatevariable', foreign_key: :master_id
hope help.
Comments
Post a Comment