belongs_to. Association methods don't pass data to DB

Hi.

I have a problem with the association methods which passed to a model through a belongs_to declaration. Here's an illustration of the issue:

GIVEN:

# migration class CreateArticlesAndAuthorsTables < ActiveRecord::Migration def self.up create_table :articles do |t| t.text :title t.integer :author_id end

create\_table :authors do |t|
  t\.text :name
end

end

def self.down drop_table :articles drop_table :authors end end

# articles model class Article < ActiveRecord::Base belongs_to :author end

# authors model class Author < ActiverRecord::Base has_many :articles end

WHEN:

Article.create(:title => 'one').author = Author.create(:name => 'Pavel')

Article.create(:title => 'two').author = Author.find(:first, :conditions => {:name => 'Pavel'})

THEN

select * from authors;

 id = 1

name = Pavel

select * from articles;

       id = 1
    title = &#39;one&#39;

author_id = null

       id = 2
    title = &#39;two&#39;

author_id = null

Why do I have null values instead of ids as foreign keys in the articles table?

Thanks.

Ruby 1.9.2; Rails 2.3.8.

I got it.

It should to break the creation statements onto a few steps:

WHEN:

one = Article.new(:title => 'one')

one.author = Author.new(:name => 'Pavel')

one.save

two = Article.new(:title => 'two')

two.author = Author.find(:first, :conditions => {:name => 'Pavel'})

two.save

THEN:

select * from authors;

     id = 1 name = Pavel

select * from articles;

           id = 1         title = 'one' author_id = 1

           id = 2         title = 'two' author_id = 1

Have a look at author.articles.build which will build a new article for an author and save some messing about.

Colin

I was most interested about that methods which are added by belongs_to declaration not has_many.

Anyway, thanks for help, Colin.