Reputation: 95
I am a beginner learning Ruby on Rails. Apologies if this question is very obvious...
I have two resources:
books and book_pages
A book has several pages and I have set up the belongs_to and has_many associations within the models. In the controller for book pages, how do I create a new book_page under this association? I currently have:
class BookPagesController < ApplicationController
...
def new
@book_page = BookPage.new
end
end
...
Also, how would I need to set up the corresponding view to create a new page?
Upvotes: 0
Views: 43
Reputation: 7725
I encourage you to test things on rails console
, it's really useful for debugging. ActiveRecord::Base models can be initialized with associations like this:
Book.create(
title: "TITLE",
book_pages: [
{ text: "blabllblablalblab", number: 1) },
{ text: "kasdhfkjahwkqjrgs", number: 2) }
# ....
]
)
@fotanus answer is equally valid. http://api.rubyonrails.org/classes/ActiveRecord/Base.html
Upvotes: 0
Reputation: 20116
Generally speaking, you would need to use a code like this:
book = Book.find(book_id)
book.book_pages.create(page_number: 1, footnote: "yey")
But note that you need to have the book id somehow in your request.
I strongly advise you to stop muddling through and read the rails guides, because rails uses convention over configuration which can be very confusing if you are not up to read the documentation.
Upvotes: 1