当我尝试访问我的帖子时,我在heroku上遇到了问题。日志说:
Rendered posts/index.html.erb within layouts/application (920.6ms)
2015-11-06T09:39:41.716328+00:00 app[web.1]: Completed 500 Internal Server Error in 936ms (ActiveRecord: 42.1ms)
2015-11-06T09:39:41.720223+00:00 app[web.1]:
2015-11-06T09:39:41.720226+00:00 app[web.1]: ActionView::Template::Error (undefined method `email' for nil:NilClass):
2015-11-06T09:39:41.720227+00:00 app[web.1]: 22: <dt> <%= post.body %> </dt>
2015-11-06T09:39:41.720227+00:00 app[web.1]: 23: <dd><%= post.tags %> </dd>
2015-11-06T09:39:41.720228+00:00 app[web.1]: 24: </dl>
2015-11-06T09:39:41.720229+00:00 app[web.1]: 25: <%= gravatar_for post.user, size: 40%> Created by <b><%= post.user.name if post.user %></b>
2015-11-06T09:39:41.720229+00:00 app[web.1]: 26: </td>
2015-11-06T09:39:41.720230+00:00 app[web.1]: 27:
2015-11-06T09:39:41.720231+00:00 app[web.1]: 28: <div>
2015-11-06T09:39:41.720231+00:00 app[web.1]: app/helpers/users_helper.rb:3:in `gravatar_for'
在localhos:3000/posts
它运作良好,错误只出现在heroku上。
我在开发和生产中都使用PostgreSQL。
这是我的routes.rb:
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :posts
root 'posts#index'
match '/signup', to: 'users#new', via: 'get'
match '/signin', to: 'sessions#new', via: 'get'
match '/signout', to: 'sessions#destroy', via: 'delete'
我的帖子的一部分#index:
<div class="show_posts">
<table>
<% @posts.each do |post| %>
<td>
<dl> <%= post.title %>
<dt> <%= post.body %> </dt>
<dd><%= post.tags %> </dd>
</dl>
<%= gravatar_for post.user, size: 40%> Created by <b><%= post.user.name if post.user %></b>
</td>
users_helper.rb:
module UsersHelper
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
任何想法如何解决问题?
答案 0 :(得分:3)
问题出在gravatar_for
内,你打电话给......
Digest::MD5::hexdigest(user.email.downcase)
所需的user
对象不存在。
当您引用时,posts#index
模型中的引起:
<%= gravatar_for post.user, size: 40%> Created by <b><%= post.user.name if post.user %>
根据评论中的建议,这可能是由于您的user
没有关联的post
对象。
立即修复将使用一些条件逻辑来确定user
是否存在(您已经做过,但仅针对post.user.name
输出):
<% if post.user %>
<%= gravatar_for post.user, size: 40 %> Created by <b><%= post.user.name %>
<% end %>
或者,您可能希望通过使用验证来确定所有帖子都是用户,以确定是否设置了关联对象:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :posts, inverse_of: :user
end
#app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user, inverse_of: :posts
validates :user, present: true
end