Nemo
Nemo

Reputation: 3164

has_many relationship not working in a fixture

My user model:

class User < ActiveRecord::Base
  has_many :articles, :dependent => :destroy
end

Article Model:

class Article < ActiveRecord::Base
  belongs_to :user
end

Article fixture:

one:
  url: http://www.google.com/
  title: Sample Title
  user: default

User fixture:

default:
  email: [email protected]
  name: Test User

Trying Article.first.user in a test case works fine, but if I try to get the opposite relationship working with the following in my User fixture:

default:
  email: [email protected]
  name: Test User
  articles: one

I get the following error:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "articles" of relation "users" does not exist

Upvotes: 1

Views: 758

Answers (1)

Zero Fiber
Zero Fiber

Reputation: 4465

You dont need to add another line in the users fixture to specify a lists of articles. All you need to do is specify the user in the article fixture (which sets the user_id column for the article) and Rails figures out the articles for a user using that foreign key.

So, your articles fixture should be:

default:
  email: [email protected]
  name: Test User

Upvotes: 1

Related Questions