Вопрос

I'm creating forum software using Ruby on Rails. I'm stuck on adding seed data to my database with the correct database relations.

A forum has many topics, and a topic belongs to a forum. That is a sample of one of the relationships.

So far, all I know how to do is create an instance that doesn't relate to any of the other tables in the database such as:

Forum.create(attributes {})

The point of this is so my nested routes will work properly: /forums/:forum_id/topics/:id

Это было полезно?

Решение

There are a few ways to do this.

In db/seeds.rb add something like:

form = Forum.create(attributes {})
form.topics.create(attributes{})

or

form = Forum.create(attributes {})
topic1 = Topic.create(attributes{})
topic2 = Topic.create(attributes{})

form.topics << topic1
form.topics << topic2

Then when you want to seed your db just run:

rake db:seed
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top