Rails 4 - 链接模型关联以访问关联方法

Rails 4 - chaining model associations to access associated methods

我有用户、配置文件和组织请求的模型。这些协会是:

用户

has_one :profile, dependent: :destroy
has_one :organisation_request, through: :profile 
    accepts_nested_attributes_for :organisation_request

简介

belongs_to :user
belongs_to :organisation

组织请求

belongs_to :profile
# belongs_to :user#, through: :profile  
belongs_to :organisation

在我的用户模型中,我有一个名为 full_name 的方法(我用它来格式化用户名的表示形式。

我正在尝试在我的 organisation_requests 模型中访问 full_name 方法。

我试图通过在我的组织请求模型中编写以下方法来做到这一点:

def related_user_name
    self.profile.user.full_name
end

当我尝试在我的组织请求索引中使用它时,如下所示:

          <%= link_to orgReq.related_user_name, organisation_request.profile_path(organisation_request.profile.id) %>

我收到一条错误消息:

undefined method `user' for nil:NilClass

当我尝试在 rails 控制台中使用这个想法时,使用:

o = OrganisationRequest.last

  OrganisationRequest Load (0.4ms)  SELECT  "organisation_requests".* FROM "organisation_requests"  ORDER BY "organisation_requests"."id" DESC LIMIT 1
 => #<OrganisationRequest id: 2, profile_id: 1, organisation_id: 1, created_at: "2016-08-01 22:48:52", updated_at: "2016-08-01 22:48:52"> 
2.3.0p0 :016 > o.profile.user.formal_name
  Profile Load (0.5ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."id" =  LIMIT 1  [["id", 1]]
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT 1  [["id", 1]]
 => " John Test" 

这个概念似乎在控制台中有效? 谁能看出我哪里出错了?

您是否检查过您的所有组织请求都有配置文件?可能这不是最佳做法,请尝试使用 profile.try(:user).try(:full_name)

不要链接方法,这是一种不好的做法,它违反了 Law of Demeter。最好的选择是使用delegate。所以而不是:

def related_user_name
  self.profile.user.full_name
end

您可以拥有:

class OrganisationRequest
  belongs_to :profile
  has_one :user, through: :profile

  delegate :full_name, to: :user, allow_nil: true, prefix: true
end

然后你可以只调用 organisation_request.user_full_name 它会通过配置文件>用户并调用 full_name (你不会得到 undefined 因为 allow_nil: true 会"cover"它)

有关 delegate here 的更多信息。