大家好,这个错误让我头疼了好几天,我真的不知道发生了什么。所以,我有两个模型:User
和Composition
。作品有belongs_to :user
,用户有has_many :compositions
和一个控制器,当我尝试从作曲家的所有者(用户)获取用户ID时,会出错。
错误
undefined method `id' for nil:NilClass
<%= link_to profile_path(compos.user.id), class: 'ui-btn btn-small' do %>
<span class="icon-export"></span>visitar perfil</a>
<% end %>
组合物
class Composition < ApplicationRecord
belongs_to :user
validates :title, presence: true, :length => {maximum: 120}
validates :description, presence: true
has_attached_file :thumbnail
validates_attachment_content_type :thumbnail, content_type: /\Aimage/
validates_attachment_file_name :thumbnail, matches: [/png\Z/, /jpe?g\Z/]
do_not_validate_attachment_file_type :thumbnail
end
用户
class User < ApplicationRecord
has_many :compositions
rolify
devise :database_authenticatable, :omniauthable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
mount_uploader :avatar, AvatarUploader
# Validações
validates_integrity_of :avatar
validates_processing_of :avatar
validates_format_of :username, :with => /[\w]+/
validates_length_of :username, :in => (5..32)
validates_uniqueness_of :username
#Previne que o avatar tenha um tamanho maior de 2MB
private
def avatar_size_validation
errors[:avatar] << "should be less than 2MB" if avatar.size > 2.megabytes
end
end
控制器
class StaticPagesController < ApplicationController
before_filter :authenticate_user!
def index
@compositions = Composition.all.order('created_at desc').limit(4)
end
end
答案 0 :(得分:2)
您可以设置条件以检查是否存在compos.user
。
<% if compos.user %>
但是,我认为你正在开发环境
,似乎它的数据不一致您需要确保每个composition
user_id必须存在。
class Composition < ApplicationRecord
belongs_to :user
validates :user, presence: true
end
这样你永远不会与user_id = nil