Rails仅在生产中未定义方法错误

时间:2013-07-12 23:17:41

标签: ruby-on-rails activerecord heroku

我正在构建一个类似于hackernews的应用来学习Rails。一切都在开发中,但是当我在heroku上部署时,我收到以下错误:

Processing by ArticlesController#index as HTML
2013-07-12T23:07:52.084981+00:00 app[web.1]: ActionView::Template::Error (undefined method       `username' for nil:NilClass):
2013-07-12T23:07:52.082828+00:00 app[web.1]: Completed 500 Internal Server Error in 122ms
2013-07-12T23:07:52.084981+00:00 app[web.1]:     9:     <%= pluralize(article.votes.count, 'vote') %>
2013-07-12T23:07:52.084981+00:00 app[web.1]:     12:   </div>
2013-07-12T23:07:52.084981+00:00 app[web.1]:     10:     by <%= link_to article.user.username, profile_path(user_id: article.user.id) %>
2013-07-12T23:07:52.084981+00:00 app[web.1]:     11:     <%= time_ago_in_words(article.created_at) %> ago |
2013-07-12T23:07:52.084981+00:00 app[web.1]:     7:   </div>

这是我的用户模型:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username
  # attr_accessible :title, :body

  validates :username, presence: true, uniqueness: true

  has_many :votes
  has_many :articles
  has_many :comments

  def already_voted_on?(id)
    self.votes.where(votable_id: id).count > 0
  end
end

这是我的索引视图(第10行抛出错误)。由于某种原因,即使它在开发中工作,它也不会识别用户的“用户名”属性:

<div class="articles">
  <% @articles.each do |article| %>
  <div class="title">
    <%= link_to image_tag('votearrow.gif'), votes_path(votable_id: article.id, value: 1, votable_type: "Article"), method: :post %>
    <%= link_to article.title, article.url %>
    <%= image_tag("http://www.google.com/s2/favicons?domain_url=" + article.url) %>
  </div>
  <div class="submitted-by">
    <%= pluralize(article.votes.count, 'vote') %>
by <%= link_to article.user.username, profile_path(user_id: article.user.id) %>
    <%= time_ago_in_words(article.created_at) %> ago |
   </div>
   <div class="comments">
     <%= link_to pluralize((article.comments.count), 'comment'), article_path(id: article.id) %>
  </div>
      <br><br>
      <% end %>
</div>

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

用户名不是设计字段,所以您可能忘记在生产环境中运行迁移?

答案 1 :(得分:1)

问题是heroku没有更新我的最新迁移(AddUserIdToArticles)。我通过删除数据库中的列,再次添加它并运行heroku restart来修复此问题。