Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Should I Build a has_one through Association?

For a has_one association I can build an association like this:

foo.build_bar()

How should I build a has_one, through: association?

For example:

class Foo

  has_one :bar
  has_one :baz, through: :bar

end

How should I build baz? In this example foo.build_baz gets me a No Method Error.

Documentation here says:

When you declare a has_one association, the declaring class automatically gains four methods related to the association:

association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})

However this doesn't seem to be the case. Using Pry to introspect an instance of Foo I can see no such method is added as it would be on a has_one without a through:.

like image 646
Undistraction Avatar asked Oct 28 '13 15:10

Undistraction


1 Answers

Seems that one possibility is to do:

foo.build_bar().build_baz()
foo.save!
like image 84
Undistraction Avatar answered Oct 14 '22 07:10

Undistraction