51. find a note by id
/note/3
def show
@note = Note.find(params[:id])
end
52. find a note of the current user
/note/3
@note = Note.find_by_id_and_user_id(
params[:id], current_user.id)
raise ActiveRecord::RecordNotFound unless @note
55. hard to notice
the luck of condition!
@note = Note.find(params[:id])
@note = Note.find_by_id_and_user_id(
params[:id], current_user.id)
@note = Note.written_by(
current_user).find(params[:id])
73. what’s the filter?
• the separated logic which would be
called around action
• declarative
74. find the group in a filter
class GroupNotesController < ApplicationController
before_filter :find_group
.......actions ......
private
def find_group
@group = Group.find(params[:group_id])
end
end
80. safe if it starts from @group
def index
@notes = @group.notes.paginate(:page =>
params[:page])
end
def show
@note = @group.notes.find(params[:id])
end
111. the logic
processing other models
def update
generate_tags(@note)
end
private
def generate_tags(note)
tags = Tag.extract(note.body)
note.tag_list = tags.join(',')
end
113. put it into model’s callback
class Note < ActiveRecord::Base
before_save :generate_taggings
private
def generate_taggings
return unless auto_tagging
tags = Tag.extract(body)
self.tag_list = tags.join(',')
end
end
114. what’s the model’s callback?
• methods called before/after save or
destroy
115. Rails Model You
normal method call
save
(validation)
before_save
do saving
after_save
117. now we’ve done it !
• easy to test
• easy to reuse
• readable, easy to find the target codes
118. other patterns
• multi levels for validation
• design & coding policy for STI
• use owner object’s attributes in association
• how to make routes.rb a little readable