Rails - 从发布日期后的索引页面中删除事件信息(发生之后)

时间:2016-07-07 16:34:47

标签: ruby-on-rails ruby ruby-on-rails-4

我正在建立一个活动网站,并在索引页面上显示所有活动(由图片,标题和日期表示)。我想知道我需要写什么代码才能在索引页面发生后删除它们。我是否写了验证方法?它是模型/控制器方法吗?

这是我当前的活动模型和控制器代码 -

Event.rb

class Event < ActiveRecord::Base

belongs_to :category
belongs_to :user
has_many :bookings
has_many :comments


has_attached_file :image, styles: { medium: "300x300>" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/


validates :title, :description, :location, :date, :time, :number_of_spaces, :price_pennies, :category_id, presence: true
validates :title, length: { minimum: 4 }
validates :description, length: { maximum: 250, too_long: "%{count} characters is the maximum allowed" }


monetize :price_pennies
# required for money-rails gem to function

end

events_controller.rb

class EventsController < ApplicationController
before_action :find_event, only: [:show, :edit, :update, :destroy,]
# the before_actions will take care of finding the correct event for us
# this ties in with the private method below
before_action :authenticate_user!, except: [:index, :show]
# this ensures only users who are signed in can alter an event

def index
    if params[:category].blank?
        @events = Event.all.order("created_at DESC")
    else
        @category_id = Category.find_by(name: params[:category]).id
        @events = Event.where(category_id: @category_id).order("created_at DESC")
    end
    # The above code = If there's no category found then all the events are listed
    # If there is then it will show the EVENTS under each category only
end

在控制器中,我通过降序设置事件。我需要编写代码,一旦它发生就会从索引页面中删除一个事件。我还有一个用户个人资料页面,其中显示了他们创建的所有用户事件,因此这将充当他们所有事件的存档。它只是需要删除它们的索引页面。

2 个答案:

答案 0 :(得分:1)

添加名为:time的日期时间字段。确保在创建事件时将:time属性设置为事件发生的时间。

完成后,您可以在事件模型上添加范围。

# You can call the scope whatever.
# :happened is the boolean field on the events table.
scope :not_yet_done, -> { where('time >= ?', Time.current) } 

在索引操作中:

def index
  if params[:category].blank?
    @events = Event.not_yet_done.order("created_at DESC")
  else
    @category_id = Category.find_by(name: params[:category]).id
    @events = Event.not_yet_done.where(category_id: @category_id).order("created_at DESC")
  end
end

答案 1 :(得分:0)

你可以在同一个方法中传递一个额外的参数并实现它。它将检查具有类别id的事件是否插入了日期或时间(大于当前日期或时间)。

def index
    if params[:category].blank?
        @events = Event.all.order("created_at DESC")
    else
        @category_id = Category.find_by(name: params[:category]).id
        @events = Event.where(category_id: @category_id, time:  ">= Time.now.zone").order("created_at DESC")
    end
end