0

所以,我所指的索引在songs#index.html.erb 中。

我想添加这样的一行:

posted by <%= song.user.email %> <%= time_ago_in_words(song.created_at) + " ago" %>

目前正在返回:

undefined method `email' for nil:NilClass

Song.rb 片段

class Song < ActiveRecord::Base

   extend FriendlyId
    friendly_id :title, use: :slugged

  acts_as_voteable

  belongs_to :user, class_name: User, foreign_key: :user_id
  has_many :comments, :dependent => :destroy
  has_many :genre_songs
  has_many :genres, through: :genre_songs

User.rb 代码片段

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

  has_many :songs
  has_many :comments

模式片段

create_table "users", id: false, force: true do |t|
    t.integer  "id",                                  null: false
    t.string   "email",                  default: ""
    t.string   "encrypted_password",     default: ""
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "admin"
    t.string   "provider"
    t.string   "uid",                                 null: false
    t.string   "username"
  end

  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree

 create_table "songs", force: true do |t|
    t.string   "title"
    t.string   "artist"
    t.text     "url"
    t.string   "track_file_name"
    t.string   "track_content_type"
    t.integer  "track_file_size"
    t.datetime "track_updated_at"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "plusminus"
    t.string   "slug"
  end

  add_index "songs", ["slug"], name: "index_songs_on_slug", unique: true, using: :btree
4

1 回答 1

0

您在索引中列出的一首歌曲似乎没有关联user,因此song.user返回nil

为避免这种情况,您应该验证Song模型中是否存在用户,或检查用户是否存在于视图中,如下所示:

<% if song.user %>
  posted by <%= song.user.email %> <%= time_ago_in_words(song.created_at) + " ago" %>
<% end %>

该方法取决于您的应用程序逻辑。

于 2013-08-18T11:42:47.043 回答