Skip to content

Instantly share code, notes, and snippets.

@vajapravin
Forked from i-arindam/1_user.rb
Last active January 5, 2018 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vajapravin/bc839d49c092c5fa44893876ab25d2f9 to your computer and use it in GitHub Desktop.
Save vajapravin/bc839d49c092c5fa44893876ab25d2f9 to your computer and use it in GitHub Desktop.
class User < ApplicationRecord
has_many :posts
has_many :comments
# id :integer not null, primary key
# name :string(50) default("")
end
class Post < ApplicationRecord
belongs_to :user
has_many :comments
# id :integer not null, primary key
# user_id :integer
# content :text default("")
# created_at :datetime
end
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
# id :integer not null, primary key
# user_id :integer
# post_id :integer
# content :text default("")
# created_at :datetime
end
class NewsfeedController < ApplicationController
# JSON endpoint that returns an array of Post objects in order of
# newest first, to oldest last. Each Post contains a User object
# (the author of the Post), and an array of Comments. Each Comment
# will also include the User object of the Comment's author.
# TODO: Newsfeed endpoint here
include ApplicationHelper
def index
render json: fetch_newsfeeds(params[:page] || 1, 10)
end
end
[
{
"type": "Post",
"content": "First post",
"user": {
"type": "User",
"name": "Luke"
},
"comments": [
{
"type": "Comment",
"user": {
"type": "User",
"name": "Leia"
},
"content": "First comment"
},
{
"type": "Comment",
"user": {
"type": "User",
"name": "Han"
},
"content": "Second comment"
},
]
},
{
"type": "Post",
"content": "Second post",
"user": {
"type": "User",
"name": "Darth Vader"
},
"comments": [
{
"type": "Comment",
"user": {
"type": "User",
"name": "Boba Fett"
},
"content": "Third comment"
},
{
"type": "Comment",
"user": {
"type": "User",
"name": "Jabba"
},
"content": "Fourth comment"
},
]
}
]
# /views/newsfeed/_comment.json.jbuilder
json.type comment.class.name
json.user format_user(comment.user)
json.content comment.content
# /views/newsfeed/_post.json.jbuilder
json.type post.class.name
json.content post.content
json.user format_user(post.user)
json.comments post.comments, partial: 'comment', as: :comment
module ApplicationHelper
def format_user user
{type: user.class.name, name: user.name}
end
def fetch_newsfeeds(page, limit)
@posts = Post.order(:created_at).paginate(page: page, per_page: limit)
render_to_string(template: "/newsfeed/feed.json.jbuilder", locals: { posts: @posts}, format: :json)
end
end
# /views/newsfeed/feed.json.jbuilder
json.array! @posts, partial: 'post', as: :post
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment