Ruby on Rails: has_many through frustrations

Posted by Joe Cairns on Stack Overflow See other posts from Stack Overflow or by Joe Cairns
Published on 2010-05-13T18:46:00Z Indexed on 2010/05/13 20:54 UTC
Read the original article Hit count: 183

I'm having a frustrating problem with a has_many through: namely the fact that the through models are not created until save. Unfortunately, I need to set data on these models prior to saving the parent.

Here's the loose setup:

class Wtf < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end

class Bar < ActiveRecord::Base
  has_many :wtfs
  has_many :foos, :through => :wtfs
end


class Foo < ActiveRecord::Base
  has_many :wtfs
  has_many :bars, :through => :wtfs

  def after_initialize
    Bar.all.each do |bar|
      bars << bar
    end
  end

end

Everything is fine except that I need to access the "wtf"'s prior to save:

f = Foo.new => #

f.bars => [list of bars]

empty list here

f.wtfs => []

f.save! => true

now I get stuff

f.wtfs => [list of stuff]

I even went so far as to explicitly create the wtfs doing this:

 def after_initialize
    Bar.all.each do |bar|
      wtfs << Wtf.new( :foo => self, :bar => bar, :data_i_need_to_set => 10)
    end
  end

This causes the f.wtfs to be populated, but not the bars. When I save and retrieve, I get double the expected wtfs.

Anyone have any ideas?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about has-many-through