2

我有事件模型。我有 3 个链接作为过去事件、即将发生的事件和当前事件。

这 3 个链接被路由到 events_url 即索引操作和 den 到索引视图。


以下是事件控制器索引操作的代码...

def index

      @today = Event.find (:all, :conditions => ['(start_date  = current_date)'], :order => 'start_date ')

      @past  = Event.find (:all, :conditions => ['start_date < ?', current_date], :order => 'start_date')

      @events  = Event.find( :all, :conditions => ['start_date > ?', current_date], :order => 'start_date')

end

我想将@today 变量数据传递给 Currentevents 链接上的索引视图,Pastevent 链接上的@past 数据和即将到来的事件链接上的 @event 数据。但我无法在各个链接上传递不同的变量。我怎样才能实现 dis?


以下是索引视图的代码:

- content_for :title do
   Listing Events
 - content_for :div do
   Listing Events
 - content_for :brand_img do
   %img{:src => "images/lifestyle.gif", :height => "35"}
 - @events.each do |event|
   %ol.hoverbox
     %li.increase
       = link_to image_tag(event.photo.url), event_path(event)
       .abc
         = event.name
       %br/
      .bca
         = event.start_date
         |
         = event.start_time
         /|
         /= link_to " ".html_safe, event_path(event), :method => :delete, :class => "del-16", :confirm=>"Are u sure?", :title => "Delete", :style => "text-decoration:none;"

由于在 dis 视图中我指的是 ti @events 变量,它仅显示即将发生的事件...我如何更改不同链接上的 dis 变量...

4

1 回答 1

4

您可以使用查询参数来执行此操作:您只需将附加参数传递给 link_to 方法,例如:

<%= link_to "Past events", events_path(view: "past") %>
<%= link_to "Today's events", events_path(view: "today") %>
<%= link_to "All events", events_path %>

然后在您的控制器中,您可以执行以下操作:

def index
  case params[:view]
  when 'past'
    @past  = Event.find (:all, :conditions => ['start_date < ?', current_date], :order => 'start_date')
  when 'today'
    @today = Event.find (:all, :conditions => ['(start_date  = current_date)'], :order => 'start_date ')
  else
    @events  = Event.find( :all, :conditions => ['start_date > ?', current_date], :order => 'start_date')
  end
end

但是,您还应该考虑通过在控制器中添加相应的 RESTful 操作来遵循 RESTful 方法:

在 config/routes.rb 中:

resources :events do
  collection do
    get 'past'
    get 'today'
  end
end

然后在您的控制器中,您必须定义不同的操作:

def index
  @events  = Event.find( :all, :conditions => ['start_date > ?', current_date], :order => 'start_date')
end

def past
  @events  = Event.find (:all, :conditions => ['start_date < ?', current_date], :order => 'start_date')
end

def today
  @events = Event.find (:all, :conditions => ['(start_date  = current_date)'], :order => 'start_date ')
end

那么在你看来:

<%= link_to "Today's events", todays_event_path %>
<%= link_to "Past events", past_event_path %>
<%= link_to "All events", event_path %>

无论您选择哪种方法,您都应该首先阅读本指南:http: //guides.rubyonrails.org/routing.html

顺便说一句,您还应该考虑在模型中使用命名范围,而不是在控制器中查询它(这样您就可以保持瘦身): http: //guides.rubyonrails.org/active_record_querying.html#scopes

这是我在这里的第一个答案,所以我希望能有所帮助:)

于 2012-04-30T13:28:44.150 回答