0

我正在制作一个 Rails 应用程序,人们可以在其中关注其他人。我在数据库中伪造了大约 100 个用户。我使用 faker gem 通过以下代码将虚假用户和虚假关系上传到数据库:

def make_relationships
  users = User.all
  user  = users.first
  followed_users = users[2..50]
  followers      = users[3..40]
  followed_users.each { |followed| user.follow!(followed) }
  followers.each      { |follower| follower.follow!(user) }
end

这应该使用户 1 关注用户 2-50,用户 1 关注用户 3-40。但是,我认为这不会发生。当我访问用户 3-51 的个人资料页面时,它显示“取消关注”按钮,这意味着所有这些用户都被 1 关注。我不确定为什么 51 包含在其中。出于某种原因,当我转到用户 2 或任何 51 岁以上用户的个人资料时,我得到:

undefined method `model_name' for NilClass:Class
Extracted source (around line #1):

1: <%= form_for(current_user.relationships.find_by_followed_id(@user.id)) do |f| %>
2:   <div><%= f.hidden_field :followed_id %></div>
3:   <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
4: <% end %>

谁能告诉我为什么我无法访问 51 岁以上的任何个人资料页面?以下是相关代码的其余部分:

关系模型:

class Relationship < ActiveRecord::Base
  attr_accessible :followed_id, :follower_id

  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"

  validates :follower_id, presence: true
  validates :followed_id, presence: true
end

用户型号:

 class User < ActiveRecord::Base
 has_many :microposts, dependent: :destroy

 has_many :relationships, foreign_key: "follower_id", dependent: :destroy
 has_many :followed_users, through: :relationships, source: :followed

 has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy
 has_many :followers, through: :reverse_relationships, source: :follower
 attr_accessible :email, :name, :password, :password_confirmation, :remember_token

关注部分视图:

<%= form_for(current_user.relationships.find_by_followed_id(@user.id)) do |f| %>
    <div><%= f.hidden_field :followed_id %></div>
    <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>

取消关注部分视图:

<%= form_for(current_user.relationships.find_by_followed_id(@user),
    html: {method: :delete}) do |f| %>
    <%=f.submit "Unfollow", class: "btn btn-large" %>
<% end %>

遵循呈现上述两个部分的表单:

<% unless current_user?(@user) %>
  <div id="follow_form">
  <% if current_user.following?(@user) %>
    <%= render 'unfollow' %>
  <% else %>
    <%= render 'follow' %>
  <% end %>
  </div>
<% end %>

顺便说一句,如果这可以帮助任何人解决这个问题,这来自 Michael Hardtl 教程。

4

1 回答 1

0

根据错误消息,您传递的 current_user 对象很可能是 nil

于 2013-10-11T19:54:58.513 回答