While delving into ruby's nested models I encountered an issue.
Consider the following scenario,
I have the following models:
- Author
- Book
With the following specifications:
Author:
class Author < ActiveRecord::Base
attr_accessible :name
has_many :books, dependent: :destroy
accepts_nested_attributes_for :books #I read this is necessary here: http://stackoverflow.com/questions/12300619/models-and-nested-forms
# and some validations...
end
Book:
class Book < ActiveRecord::Base
attr_accessible :author_id, :name, :year
belongs_to :author
#and some more validations...
end
I would like to add a book to an author. Here is my authors_controller:
def new_book
@author = Author.find(params[:id])
end
def create_book
@author = Author.find(params[:id])
if @author.books.create(params[:book]).save
redirect_to action: :show
else
render :new_book
end
end
And this is the form with which I try doing it:
<h1>Add new book to <%= @author.name %>'s collection</h1>
<%= form_for @author, html: { class: "well" } do |f| %>
<%= fields_for :books do |b| %>
<%= b.label :name %>
<%= b.text_field :name %>
<br/>
<%= b.label :year %>
<%= b.number_field :year %>
<% end %>
<br/>
<%= f.submit "Submit", class: "btn btn-primary" %>
<%= f.button "Reset", type: :reset, class: "btn btn-danger" %>
<% end %>
Problem: When I type in the data and click "submit" it even redirects me to the correct author, but it doesn't save a new record for that author. After a lot of research I can't seem to find what I am doing wrong here.