Skip to content

Instantly share code, notes, and snippets.

@seancdavis
Last active September 27, 2018 11:31
Show Gist options
  • Save seancdavis/c4f8c81d216f3893f16d to your computer and use it in GitHub Desktop.
Save seancdavis/c4f8c81d216f3893f16d to your computer and use it in GitHub Desktop.
rails scaffold that belongs to a Devise user model
<% # app/views/posts/_post.html.erb %>
<article>
<h2><%= post.title %></h2>
<!-- ... -->
</article>
<% # app/views/posts/index.html.erb %>
<h1><%= current_user %>'s Posts</h1>
<% # `render @posts` knows to automatically loop through @posts and render %>
<% # app/views/posts/_post for each object in the array, with `post` as the object %>
<%= render @posts %>
# app/models/post.rb
class Post < ActiveRecord::Base
# ------------------------------------------ Associations
belongs_to :user
# ...
end
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
# Devise method for ensuring user is logged in before accessing any of the
# methods (actions) within this controller
before_filter :authenticate_user!
before_action :find_post, :only => [:show,:edit,:update,:destroy]
def index
# since we know the user is logged in, we now have access to the
# `current_user` object, which the `User` object of the user that is logged
@posts = current_user.posts
end
# ...
private
def find_post
# by calling posts in this manner vs. `Post.find_by_id(params[:id])`, we
# ensure we won't end up with a post belonging to another user
current_user.posts.where(:id => params[:id]).first
end
end
# app/models/user.rb
class User < ActiveRecord::Base
# ------------------------------------------ Devise
devise :database_authenticatable, :recoverable, :rememberable, :trackable,
:validatable
# ------------------------------------------ Associations
has_many :posts
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment