krackmoe
krackmoe

Reputation: 1763

rails insert into model and association

I got a main table and a bezirk table.

When i insert data into my main table, i want to insert data in my bezirk table as well. And the entry i am creating in bezirk, should have the id of the main table.

Main Model:

class Main < ActiveRecord::Base
   attr_accessible :category, :latlon
   has_one :bezirk
   accepts_nested_attributes_for :bezirk
end

Bezirk Model:

class Bezirk < ActiveRecord::Base
  attr_accessible :beznr, :coordinates, :district_code, :id, :name
  belongs_to :main
end

And here is how i tried to do it...

    main = Main.new(:category => "Bezirk", :latlon => 'POINT(1,2)')
    main.save
    bezirk = main.bezirks.new(:name => 'test', :beznr => 2, :district_code => 1160, :coordinates => 'POINT(1,2)')
    bezirk.save

So... how am i able to insert into bezirk, the corresponding main id!? so that i have an association between two entries...

Upvotes: 0

Views: 3182

Answers (1)

Thanh
Thanh

Reputation: 8604

You can use this:

# create main
main = Main.create(:category => "Bezirk", :latlon => 'POINT(1,2)')

# create bezirk belongs to main, so bezirk will have main_id, is id of main
bezirk = main.create_bezirk(:name => 'test', :beznr => 2, :district_code => 1160, :coordinates => 'POINT(1,2)')

Upvotes: 2

Related Questions