我對Ruby on Rails(並且已經愛上它)有點新,並試圖做出一個非常簡單的Web應用程序,它列出了提交表單和'飼料'在一個頁面上。我從Michael Hartl的精彩Rails教程中獲得了很多這些編程概念。Rails異常:Action Controller sort_by nil:NilClass當試圖錯誤處理
發帖工作正常;當表單提交時沒有表單數據(測試錯誤處理)時拋出錯誤。
對不起,這個新手問題,但我真的想學習,你的幫助是非常感謝。
我一遍又一遍地搜索這些例外,我似乎無法追查它。我認爲問題在於@posts = Post.all
這條線,我認爲它拉動了沒有保存的空郵件,但這是我可以達成的唯一結論,修復它的方式對我來說並不明顯。
如果您需要更多代碼,我很樂意發佈它,並非常感謝您的幫助!
下面是有問題的代碼,引發錯誤:
/app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all
@post = Post.new
end
def create
@post = Post.new(params[:post])
if @post.save
redirect_to '/', :flash => { :success => "Awesomesauce! Your post has been broadcast (like a boss)!" }
else
@post.destroy
render 'index'
end
end
def destroy
@post = Post.destroy
end
end
/app/models/post.rb
class Post < ActiveRecord::Base
attr_accessible :author, :location, :text
validates :author, presence: true
validates :text, presence: true, length: {maximum: 140}
end
index.html.erb(我截斷了一些ir這裏相關的代碼)
<div class="span8 center">
<%= render partial: "shared/flash_messages", flash: flash %>
<%= render 'shared/post_form' %>
<h4>Latest posts <span class="label label-info">Updated LIVE</span></h4>
<ol class="posts">
<% @posts.sort_by{|t| - t.created_at.to_i}.each do |post|%>
<li>
<span class="content"> <%= post.text %> </span>
<span class="content muted">Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.author %> in <%= post.location %>. </span>
</li>
<% end %>
/config/routes.rb
match '/', to: 'posts#index'
resources :posts
時引發的錯誤如下:
undefined method `sort_by' for nil:NilClass
Extracted source (around line #14):
11: <%= render 'shared/post_form' %>
12: <h4>Latest posts <span class="label label-info">Updated LIVE</span></h4>
13: <ol class="posts">
14: <% @posts.sort_by{|t| - t.created_at.to_i}.each do |post|%>
15: <li>
16: <span class="content"> <%= post.text %> </span>
17: <span class="content muted">Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.author %> in <%= post.location %>. </span>
我試圖用我的代碼代替你的代碼,它仍然在第14行拋出同樣的錯誤。我也嘗試過,用'render:action =>:index'代替'redirect_to'/'',甚至一個有效的帖子也會拋出相同的錯誤。任何其他想法如何解決這個問題?還應該注意,我正在運行Rails 3.2.12和Ruby 1.9.3-HEAD(cron每夜從自制軟件更新它)。 –
嘗試在'@post = Post.new(params [:post])''下面的'create'動作中加入'@posts = Post.all'。 – zeantsoi
這很完美,例外已經停止。感謝您的幫助,我真的很感激! –