Use Active Record to Create a Row on a Table that Has Foreign Keys
Posted on August 14, 2015 in Rails by Matt Jennings


Assume that the following tables in the same Active Record database:
users – -> blogs (one user can have many blogs) – -> posts (one blog can have many posts)

If a user has been added to the users table, AND that user has created one blog, below is the code that will add one post into the posts table that has the columns of id, user_id (foreign key), blog_id (foreign key), title, content, created_at, and updated_at:

Post.create(user: User.first, blog: Blog.first, title: "Title here", content: "Content here")

Leave a Reply

To Top ↑