0

使用 devise 进行身份验证,undefined method 'size' for nil:NilClass是从以下视图代码中提出的:

<% @relationships.each do |relationship| %>
  <div><%= relationship.box.size  %></div>
<% end %>

仅当我在控制器中将@relationships 定义为

@relationships = current_user.relationships

但不是当我将其定义为

@relationships = User.find(current_user.id).relationships

这两个定义不应该相同吗?

我有以下关联:

class Relationship < ActiveRecord::Base

  belongs_to :user
  belongs_to :box

end

class User < ActiveRecord::Base

  has_many: :relationships
  has_many: :boxes, through: :relationships

end

class Box < ActiveRecord::Base

  has_many: :relationships
  has_many: :users, through: :relationships

end

我希望我提供了正确的信息;这是我第一次无法找到堆栈溢出的答案。提前致谢!

4

1 回答 1

0

我在同一操作中通过 current_user (current_user.relationships.new) 创建了另一个对象:

@relationship = current_user.relationships.new
@relationships = current_user.reload.relationships #reload required

在对第一个分配进行以下更改后,可以删除 reload 调用:

@relationship = Relationship.new
@relationships = current_user.relationships

特别感谢 @AmitKumarGupta 帮助新手!

于 2012-12-29T16:58:50.163 回答