以下来自Michael Hartl的Rails教程的特写

时间:2015-01-31 01:22:31

标签: ruby-on-rails ruby-on-rails-3 devise friendly-id

我正在努力实现Hartl的RoR教程第12章中的跟随者功能。

我有这个功能,我可以登录,转到另一个用户个人资料,点击关注和(刷新页面后)我看到我现在正在关注他们。与取消相同。

但是,我的集成测试失败,Ajax不起作用,当我点击关注或取消关注时,我在Rails服务器日志中收到此错误:

Rendered users/_follow.html.erb (1.7ms)
Rendered relationships/destroy.js.erb (2.5ms)
Completed 500 Internal Server Error in 17ms
NoMethodError - undefined method `id' for nil:NilClass:

我的代码完全匹配Hartl(我认为)。但是,我在我的用户模型和Devise上使用FriendlyID,其中一个(可能是FriendlyID)导致问题。

我相信这是所有相关的代码。

任何想法都会受到赞赏......现在大约5小时左右!

控制器/ users_controller.rb

def following
@title = "Following"
@user  = User.friendly.find(params[:id])
@users = @user.following
render 'show_follow'
end

def followers
@title = "Followers"
@user  = User.friendly.find(params[:id])
@users = @user.followers
render 'show_follow'
end

控制器/ relationships_controller.rb

def create
user = User.friendly.find(params[:followed_id])
current_user.follow(user)
respond_to do |format|
  format.html { redirect_to @user }
  format.js
 end
end

def destroy
user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
respond_to do |format|
  format.html { redirect_to @user }
  format.js
end
end

模型/ user.rb

# follows a user
def follow(other_user)
active_relationships.create(followed_id: other_user.id)
end

# unfollows a user
def unfollow(other_user)
  active_relationships.find_by(followed_id: other_user.id).destroy
end

# returns true if user is following the other user
def following?(other_user)
following.include?(other_user)
end

_unfollow.html.erb

<%= form_for(current_user.active_relationships.find_by(followed_id: @user.id), 
html: { method: :delete }, remote: true) do |f| %>  
<%= f.submit "Unfollow", class: "btn" %>
<% end %>

_follow.html.erb

<%= form_for(current_user.active_relationships.build(followed_id: @user.id), remote: true) do |f| %>
<div><%= hidden_field_tag :followed_id, @user.id %></div>
<%= f.submit "Follow", class: "btn" %>
<% end %>

1 个答案:

答案 0 :(得分:4)

relationships_controller.rb您尚未定义@user变量,这就是您收到undefined method错误的原因。试试这个:

def create
  @user = User.friendly.find(params[:followed_id])
  current_user.follow(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end

def destroy
  @user = Relationship.find(params[:id]).followed
  current_user.unfollow(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end