Ruby on rails 如何添加由';user.email';到我的应用程序索引?
所以,我指的是歌曲中的索引#index.html.erb 我想添加这样一行:Ruby on rails 如何添加由';user.email';到我的应用程序索引?,ruby-on-rails,Ruby On Rails,所以,我指的是歌曲中的索引#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 FriendlyI
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
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
您在索引中列出的某首歌曲似乎没有与其关联的
用户
,因此歌曲.user
返回nil
为了避免这种情况,您应该在Song
模型中验证用户的存在,或者检查视图中是否存在用户,如下所示:
<% if song.user %>
posted by <%= song.user.email %> <%= time_ago_in_words(song.created_at) + " ago" %>
<% end %>
邮寄人
这种方法取决于您的应用程序逻辑 啊,我想起来了,这是有道理的。我使用种子数据来填充我的测试环境。那么,这在与歌曲相关的真实用户的制作中是否可行?只是想确保代码看起来正确,是吗?@Apane101我把答案扩大了一点,以涵盖(我想)你的问题。
<% if song.user %>
posted by <%= song.user.email %> <%= time_ago_in_words(song.created_at) + " ago" %>
<% end %>