如何显示帖子的日期?

时间:2015-02-11 12:00:03

标签: ruby-on-rails ruby

我正在创建一个简单的工作委员会,并希望以格式显示帖子的创建日期 - '发布于:2015年2月11日'

我想在两个地方展示它,在我的索引(index.html.erb)中发布帖子和各个帖子页面(show.html.erb)

我目前的代码如下:

index.html.erb -

    <p><%= link_to "Add a Position", new_job_path %></p>

    <% @jobs.each do |job| %>
        <div class="job">
            <%= link_to job.position, job %>
            <br><br>
            <ul class="entry_list">
                <li>Company: <%= job.company %></li>
                <li>Salary: <%= job.salary %></li>
                <li>Contract Type: <%= job.contract %></li>
                <li>City: <%= job.city %></li>
                <li>Expiry date: <%= job.expirydate %></li>
                <li>Job Type: <%= job.jobtype %></li>
            </ul>
        </div>
    <% end %>

    <p><%= paginate @jobs %></p>

show.html.erb -

    <%= @job.position %>
    <ul>
      <li>Company: <%= @job.company %></li>
      <li>Salary: <%= @job.salary %></li>
      <li>Contract Type: <%= @job.contract %></li>
      <li>City: <%= @job.city %></li>
      <li>Expiry date: <%= @job.expirydate %></li>
      <li>Job Type: <%= @job.jobtype %></li>
      <li><%= @job.description %></li>
      <li>How to apply: <%= @job.apply %></li>
    </ul>

job.rb -

class Job < ActiveRecord::Base
  validates :position, presence: true
  validates :company, presence: true
  validates :salary, presence: true
  validates :companywebsite, presence: true
  validates :companytwitter, presence: true
  validates :contract, presence: true
  validates :city, presence: true
  validates :expirydate, presence: true
  validates :jobtype, presence: true
  validates :description, presence: true
  validates :apply, presence: true
  validates :contactname, presence: true
  validates :contactemail, presence: true
  validates :contactphone, presence: true
end

jobs_controller.rb -

class JobsController < ApplicationController
  def index
     @jobs = Job.page(params[:page]).per(25)
  end

  def new
     @job = Job.new
  end

  def show
     @job = Job.find(params[:id])
  end

  def create
     @job = Job.new(params.require(:job).permit(:position, :company, :salary, :companywebsite, :companytwitter, :contract, :city, :expirydate, :jobtype, :description, :apply, :contactname, :contactemail, :contactphone, ))
    if @job.save
      redirect_to root_path
    else
      render "new"
    end
  end
end

2 个答案:

答案 0 :(得分:5)

你需要使用strftime。

<%= job.created_at.strftime("#{job.created_at.day.ordinalize} %B %Y") %>

&#34;张贴于&#34;你需要静静地投入。

有关ordinalize

的更多信息

答案 1 :(得分:1)

(这是对japed's answer的补充,但评论的时间太长了)

由于您需要在多个地方使用此功能,因此您可以添加自己的时间格式:

# config/initializers/time_formats.rb
Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("#{time.day.ordinalize} %B %Y") }

并致电to_formatted_s或其别名to_s

job.created_at.to_s(:short_ordinal)
#=> "11th February 2015"