Hello! This has got to be one of those easy and obvious things, but
I’ve been beating my head against it for two days now, and can’t figure
it out.
I’m following the tutorial at
Ruby on Rails 2.1 Tutorial | Tutorialspoint, which I have
found to be quite helpful. However, I want to do things a little bit
differently, and can’t figure out how. This tutorial sets up a “Books”
table, with columns Title, Price, and Description. There is another
table called “Subjects”, with a column for Name. The two tables have a
one-to-many relationship, so the subject has many books.
The way the tutorial does it, you pre-populate the “Subjects” table with
a list of subjects, and then when you create a form to enter new data,
you choose the subjects from a drop-down list. I can get this to work
just fine, but I want to do something different: I don’t want the list
of subjects to be pre-determined, but I want to be able to enter them in
as I go.
How on earth do you do this? I haven’t found a single tutorial that
explains how to enter data into a related table without using a
drop-down list of pre-entered data!
I can do it in the console:
s=Subject.new
=> #<Subject id: nil, name: nil, created_at: nil, updated_at: nil>
s.name=“Stuff”
=> “Stuff”
s.save
=> true
Subject.find(:all)
=> [#<Subject id: 1, name: “Stuff”, created_at: “2008-07-31 20:35:58”,
updated_at: “2008-07-31 20:35:58”>]
Book.find(:all)
=> [#<Book id: 1, title: “Book”, price: 5.0, subject_id: nil,
description: “Trying to figure this out.”, created_at: “2008-07-31
20:26:11”, updated_at: “2008-07-31 20:26:11”>]
b=Book.find(id=“1”)
=> #<Book id: 1, title: “Book”, price: 5.0, subject_id: nil,
description: “Trying to figure this out.”, created_at: “2008-07-31
20:26:11”, updated_at: “2008-07-31 20:26:11”>
b.subject_id = “1”
=> “1”
b.save
=> true
Book.find(:all)
=> [#<Book id: 1, title: “Book”, price: 5.0, subject_id: 1, description:
“Trying to figure this out.”, created_at: “2008-07-31 20:26:11”,
updated_at: “2008-07-31 20:37:10”>]
But for the life of me I can’t figure out how to do it using forms.
Any help is greatly appreciated!