2013-08-26 37 views
0

我正在尝试为我的应用程序构建“精选帖子”功能。我有一个表posts与列feature_date。我正在努力设计,以便您可以点击结构为/year/month/date的网址,并显示所有具有与URL中的日期相匹配的feature_date的条目。从URL传递日期参数以筛选数据库中的条目列表

routes.rb正确地路由到posts控制器:

match "/:year/:month/:day", to: 'posts#index', via: 'get', :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ }, :as => 'post_date' 

不过,我觉得我没有正确地使用post_controller.rb

def index 
    @date = params[:year].to_s + "/" + params[:month].to_s + "/" + params[:day].to_s 
    @featured_posts = Post.find_by(feature_date: @date) 
end 

这似乎太不雅是正道在Ruby中完成。

我的看法是破的,但我认为它从控制器的:

<% @featured_posts.each do |post| %> 
<tr> 
    <td><%= post.title %></td> 
    <td><%= post.url %></td> 
    <td><%= post.user.name %></td> 
    <td><%= link_to 'Delete', post_path(post), method: :delete, data: { confirm: "Are you sure?" } %></td> 
</tr> 
<% end %> 

它抛出是undefined method 'each' for #<Post:0x007f94393bc7a0>的错误,但我相信这是因为@featured_posts将返回nil(我不知道如何确认,似乎只是为什么.each会是一个未定义的方法)。

回答

0

这是因为@featured_posts = Post.find_by(feature_date: @date)返回单个记录,而不是您所期望的记录数组。这不是因为@featured_posts是零,否则错误将会是NilClass的未定义方法'each'。你可以使用Post.find(:all, :conditions => {featured_date: @date}但这将在轨道4,5给出一个弃用警告等会Post.all(:conditions => {featured_date: @date})

为了解决这个问题使用这种代替。

@featured_posts = Post.where(featured_date: @date).to_a 

.to_a使它肯定返回一个数组。

+0

工作完美。谢谢! –