Ruby on Rails Tuesday, June 29, 2010

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

sqlite> select * from authors;
     id = 1
name = Pavel

sqlite> select * from articles;
           id = 1
        title = 'one'
author_id = null

           id = 2
        title = 'two'
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.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment