belongs_to的工作不正常
我有这样的问题: belongs_to的工作不正常
而且我有这样的代码:
user.rb:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def full_name
"lalalala"
end
end
status.rb:
class Status < ActiveRecord::Base
belongs_to :user
end
show.html.erb:
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= @status.user.full_name %>
</p>
<p>
<strong>Content:</strong>
<%= @status.content %>
</p>
<%= link_to 'Edit', edit_status_path(@status) %> |
<%= link_to 'Back', statuses_path %>
我在这里错过了什么?我无法访问full_name方法,但我不知道为什么。我是Ruby-on-Rails的新手,所以它必须是一些我不了解的简单细节。 rails版本:4.1.5;红宝石版本:2.1.2
继Marek
的评论,你也想看看使用.delegate
方法,防止Law Of Demeter
(有不止一个‘点’,以调用一个方法):
#app/models/status.rb
class Status < ActiveRecord::Base
belongs_to :user
delegate :full_name, to: :user, prefix: true
end
这会给你打电话的能力:
@status.user_full_name
有效性
由于Marek
表示,您可能没有任何与您的status
关联的user
对象。
要确定是否这是问题,你需要使用一个conditional statement检查调用它之前,如果user
物体实际存在:
<%= @status.user_full_name if @status.user.present? %>
这会给你打电话的相关user
的能力对象存在
你有你需要在您的错误信息。您的Status
记录没有关联User
记录,因此@status.user
返回nil
。
你不是已经与用户相关的@status
<%= @status.user.try(:full_name) %>
以上当没有用户关联时不会引发错误。
以上所有答案都可以解决您的查看问题。但是由于当前的代码,您可能会遇到很多问题。
几件事情,我发现,创造的问题:
1:你得到@status.user
为零。这意味着您的user_id
列(必须在那里)状态设置不正确。因此,首先设置,然后使用上面的解决方案来解救你的错误。
第二:您没有在您的状态模型中指定任何关系。您的用户模型中应该有has_many :statuses
或has_one :status
。
第3步:确保在状态表中正确填充了user_id列。尝试创建它象下面这样:
,如果您有has_one
关系:
@user_object.status.create(status_params)
,如果您有has_many
关系:
@user_object.statuses.create(status_params)
1 + ..让新的东西要知道'.delegate'方法.. – 2014-09-11 09:49:38