Sunday, 15 February 2015

Rails 4: Parent has_one Child with a specific related ChildType -



Rails 4: Parent has_one Child with a specific related ChildType -

i have parent has many children, 1 firstborn. firstborn child related childtype of "firstborn".

class parent has_many :children has_one :firstborn, -> { includes(:child_type).references(:child_type).where("child_type.name = ?", "firstborn") }, class_name: "child" end class kid belongs_to :parent belongs_to :child_type end class childtype has_many :children end

the next code not work:

parent = parent.find(1) # => <parent object> firstborn = parent.firstborn # => nil

the end goal beingness able retrieve parents , firstborn children in 1 query.

parents_and_firstborn = parent.includes(:firstborn)

i'm looking solution executes 1 query , retrieves parent , related firstborn children.

i've reviewed rails 4.0.2 api docs has_one, none of examples span across multiple tables i'm trying do.

update: 2014-10-16 14:40

the next "works" don't know why:

parent = parent.includes(:firstborn).find(1) # => <parent firstborn>

why can not retrieve firstborn after have retrieved parent, if includes(...) in original query returns it?

solution: 2014-10-16 14:50

i had attr_accessor :firstborn still stuck in parent model previous attempts solving problem. when removed unused code, has_one :firstborn ... code worked expected.

that looks correct(ish) is, should debug sql beingness executed.

i'd question merit of childtype table see here. schema seems overly complicated. why don't utilize first_born bool?

ruby-on-rails-4 rails-activerecord has-one scopes

No comments:

Post a Comment