我正在为我的用户实施一项关注功能。为此,我按照micheal hartl教程的指示 link needed ,但是我收到了这个错误:
undefined method id' for nil:NilClass <% if current_user.following?(@user) %>
这是我的用户模型
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
def following?(user)
relationships.find_by(followed_id: user.id)
end
def follow!(user)
relationships.create!(followed_id: user.id)
end
def unfollow!(user)
relationships.find_by(followed_id: user.id).destroy
end
这是我的关系模式
class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
这是我的观点
<% if current_user.id && current_user.id != user.id %>
<div id="follow_form">
<% if current_user.following?(@user) %>
<%= form_for(current_user.relationships.find_by(followed_id: @user.id),
html: { method: :delete }) do |f| %>
<%= f.submit "Unfollow", class:"unfollow-button" %>
<% end %>
<% else %>
<%= form_for(current_user.relationships.build(followed_id: @user.id)) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class:"follow-button" %>
<% end %>
<% end %>
这是用户控制器
def show
@user= User.find_by_slug(params[:id])
if @user
@posts= Post.all
render action: :show
else
render file: 'public/404', status: 404, formats: [:html]
end
end
def index
@users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))
end
答案 0 :(得分:1)
这意味着@user
为零。通过执行
@user
对象不为空
= debug @user
那应打印有关@user
对象的所有详细信息。