【发布时间】:2016-03-29 09:19:49
【问题描述】:
我只想显示创建事件的用户名。但是当我尝试时它说
undefined method `user_name' for nil:NilClass
这是我的活动.rb
class Event < ActiveRecord::Base
belongs_to :user
validates :name, presence: true
validates :description, presence: true, length: {minimum: 5}
end
这是我的 user.rb
class User < ActiveRecord::Base
has_secure_password
has_many :events
end
我正在尝试在html.erb 文件中显示用户名,如下所示。
<%= event.user.user_name %>
但是我收到了这个错误。
这是我在events_controller中的创建方法
def create
@event = current_user.events.new(event_params)
respond_to do |format|
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
else
format.html { render :new }
end
end
end
那么我应该怎么做才能在该页面中显示用户名。
谢谢
【问题讨论】:
-
如果您打算在创建后立即显示创建事件的用户名(假设您在用户表中有一个“用户名”列),请尝试在 show.html.erb 中使用
<%= @event.user.user_name %>事件。 -
现在它说 nil:NilClass 的未定义方法“用户”
-
如果问题中包含除
<%= @event.user.user_name %>以外的任何内容,请发布您的整个 show.html.erb 文件。 -
你在用设计吗?
-
我可以看到您没有该模型的
user_name字段。我相信你想拥有那个领域,但你忘了创造一个。您可以添加和迁移数据库。您究竟想在什么视图中显示它?
标签: ruby-on-rails ruby activerecord associations