我有事件模型。我有3个链接,如Pastevents,Upcoming events和currentevents。
这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链接上的过去数据和upcomingevent链接上的@event数据。但是我无法在各自的链接上传递不同的变量。如何我能实现吗?
以下是索引视图的代码:
- 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变量...
答案 0 :(得分: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
这是我在这里的第一个答案,所以我希望我可以提供帮助:)。