This is my index.html.erb file
<% @posts.each do |post| %>
<div class="post_wrapper">
<h2 class="title"><%= link_to post.title, post %></h2>
<p class="date"><%= post.created_at.strftime("%B %d, %Y") %></p>
</div>
<% end %>
I want to change the line
<p class="date"><%= post.created_at.strftime("%B %d, %Y") %></p>
to <p class="date">Submitted <%= time_ago_in_words(@post.created_at) %> Ago</p>
but it's throwing up errors. This line is working well in show page but got errors in the index page.
below is my post_controller.rb file
class PostsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :correct_user, only: [:destroy, :edit]
def search
if params[:search].present?
@posts = Post.search(params[:search])
else
@posts = Post.all
end
end
def index
@posts = Post.all.order('created_at DESC')
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :date, :time, :location))
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to root_path
end
def upvote
@post = Post.find(params[:id])
@post.upvote_by current_user
redirect_to :back
end
private
def post_params
params.require(:post).permit(:title, :date, :time, :location)
end
def correct_user
@post = current_user.posts.find_by(id: params[:id])
if @post.nil?
flash[:alert] = "Not your post!"
redirect_to :back
end
end
end
and here's my show.html.erb file,
<div id="post_content">
<h1 class="title">
<%= @post.title %>
</h1>
<p class="date">
Submitted <%= time_ago_in_words(@post.created_at) %> Ago
<!-- To show edit & delete for sign_in user
<% if user_signed_in? %>
| <%= link_to 'Edit', edit_post_path(@post) %>
| <%= link_to 'Delete', post_path(@post), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
-->
</p>
<p class="date">
<%= @post.date %>
</p>
<p class="time">
<%= @post.time %>
</p>
<p class="location">
<%= @post.location %>
</p>
<div id="comments">
<div class="btn-group pull-left">
<%= link_to like_post_path(@post), method: :put, class: "btn btn-default" do %>
<span class="glyphicon glyphicon-heart"></span>
<%= @post.get_upvotes.size %>
<% end %>
</div>
<h2><%= @post.comments.count %> Comments</h2>
<%= render @post.comments %>
<h3>Add a comment:</h3>
<%= render "comments/form" %>
</div>
答案 0 :(得分:1)
Try changing:
<p class="date">Submitted <%= time_ago_in_words(@post.created_at) %> Ago</p>
to:
<p class="date">Submitted <%= time_ago_in_words(post.created_at) %> Ago</p>
In your index action (and the associated view), you don't have the @post
variable (but you do in your show action). Instead, you have the post
variable which comes from:
<% @posts.each do |post| %>