-
Notifications
You must be signed in to change notification settings - Fork 0
11 Creating Notes
Dave Strus edited this page Nov 18, 2014
·
2 revisions
Let's add RESTful routes for notes.
config/routes.rb
resources :notesCreate NotesController with new and edit actions.
app/controllers/notes_controller.rb
class NotesController < ApplicationController
def new
@note = Note.new
end
def edit
@note = Note.find params[:id]
endCreate the views for new and edit, each rendering a form partial.
app/views/notes/new.html.erb and app/views/notes/edit.html.erb
<%= render 'form' %>The form partial needs to include a text field for title and a textarea for body_html.
_app/views/notes/form.html.erb
<%= form_for @note do |f| %>
<p>
<%= f.text_field :title %>
</p>
<p>
<%= f.text_area :body_html %>
</p>
<div class="form-actions">
<%= f.submit class: 'btn btn-default' %>
</div>
<% end %>Add create and update actions to the controller, once again using locale-based flash messages.
app/controller/notes_controller.rb
def create
@note = Note.new note_params
if @note.save
flash.now[:notice] = t('note.flash.create.success')
render :edit
else
flash.now[:alert] = t('note.flash.create.failure')
render :new
end
end
def update
@note = Note.find params[:id]
if @note.update note_params
flash.now[:notice] = t('note.flash.update.success')
else
flash.now[:alert] = t('note.flash.update.failure')
end
render :edit
endconfig/locales/en.yml
note:
flash:
create:
success: "Your note has been created!"
failure: "There was a problem creating your note."
update:
success: "Saved!"
failure: "There was a problem saving your changes."Can you create and update notes if you browse directly to the new and edit paths? Commit!
$ git add .
$ git commit -m "Create and update notes."