所以,我所指的索引是歌曲#index.html.erb。
我想添加这样一行:
posted by <%= song.user.email %> <%= time_ago_in_words(song.created_at) + " ago" %>
目前正在返回:
undefined method `email' for nil:NilClass
Song.rb snippit
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 snippit
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
架构snippits
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
答案 0 :(得分:0)
您在索引中列出的某首歌曲中似乎没有关联的user
,因此song.user
会返回nil
。
为避免这种情况,您应该在Song
模型中验证用户的存在,或检查用户是否存在于视图中,如下所示:
<% if song.user %>
posted by <%= song.user.email %> <%= time_ago_in_words(song.created_at) + " ago" %>
<% end %>
该方法取决于您的应用程序逻辑。