2013-08-26 31 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

工作完美。謝謝! –