Skip to content

Instantly share code, notes, and snippets.

@salami-art
Created November 20, 2013 20:09
Show Gist options
  • Save salami-art/7570117 to your computer and use it in GitHub Desktop.
Save salami-art/7570117 to your computer and use it in GitHub Desktop.
I can create a new book, as desired, in pair with its author by running: > book = Book.create(:title => "title", :author_attributes => {:name => "name"}, :text => "text") However, every attempt to post via http results in error: "Author can't be blank" I've already tried with: [...] <%= fields_for :author , @book.author do |ff| %> <li>Author<br>…
class Author < ActiveRecord::Base
validates :name, :presence => true
has_many :books, :inverse_of => :authors
end
class Book < ActiveRecord::Base
validates :title, :presence => true
validates :author, :presence => true
validates :text, :presence => true
before_create :fix_title
belongs_to :author, :inverse_of => :books
accepts_nested_attributes_for :author
def fix_title
self.title = self.title.titleize
end
end
class BooksController < ApplicationController
def index
@books = Book.all
respond_to do |format|
format.html
format.yaml { render text:@books.to_yaml }
format.json { render text:@books.to_json }
end
end
def show
@book = Book.find(params[:id])
respond_to do |format|
format.html
format.yaml { render text:@book.to_yaml }
end
end
def new
@book = Book.new
end
def create
# @author = Author.create(params[:name])
@book = Book.new(book_params)
if @book.save
redirect_to book_path(@book)
else
render :new
end
end
def edit
@book = Book.find(params[:id])
end
def update
@book = Book.find(params[:id])
end
private
def book_params
params.require(:book).permit(:title, :text, :author_id, :author_attributes)
end
end
<%= form_for(setup_book(@book)) do |f| %>
<% if @book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>
<ul>
<% @book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<ul>
<li>Title <br> <%= f.text_field :title %></li>
<%= fields_for :author_attributes , @book.author do |ff| %>
<li>Author<br> <%= ff.text_field :name %>
<% end %>
<li>Text <br> <%= f.text_area :text %></li>
</ul>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment