来自 User.rb 的未定义方法"跟随"



Rails 3.2 newb.

该应用程序是推特。

更新3:已经取得了进展。我在buddies.html.erb中将@phriends更改为:phriends,现在通知user don't exist自动出现。.但至少页面加载..然后"加/减"给了我"No route matches [POST] "/buddies"

更新 2:"undefined method model_name' 代表 NilClass:Class"' 代表 @phriends...我不认为rails喜欢我在一页上做很多事情。

更新:"Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id"我两次收到此错误两次。

这来自我的User.rb模型

  def following? user
self.followeds.include? user
 end
 def follow user
Relationship.create follower_id: self.id, followed_id: user.id
 end
 def unfollow user
   Relationship.destroy follower_id: self.id, followed_id: user.id
 end

到我的user_controller.rb

def buddies
@phriends = User.find_by_username(params[:username])
                if current_user.following? @phriends
                        current_user.unfollow @phriends 
                        else
                    current_user.follow @phriends 
                    end

查看/用户/好友.html.erb

<%= form_for @phriends do |f| %>
<%= f.text_field :username, placheholder:"username" %>
<%= f.submit "Add/Subtract" %>

如您所知,我正在尝试通过输入正确的用户名来关注/取消关注。

有一种感觉,我错了,因为那行不通。

控制器的另一个选项是这个...

 @phriends = User.find_by_username(params[:username])  
                if current_user.following? @phriends
                        relationship_path, method: :delete
                        else
                    @relationship
                    end
                 @relationship = Relationship.where(
                                  follower_id: current_user.id,
                                   followed_id: @user.id
                                  ).first_or_initialize if current_user

但后来它抱怨我没有身份证......无法破解最后一个问题。

顺便说一句,这是一个多合一的页面。稍微打破规则。

附言额外信用:此页面还显示了我关注的所有推文......我怎么能说,每个用户只显示最新的推文......?

如果问题仅在控制器中的未定义方法中,那么这很容易 - 您应该从current_user调用方法

def buddies
  @phriends = User.find_by_username(params[:username])
  if @phriends
    if current_user.following? @phriends
      current_user.unfollow @phriends
    else
      current_user.follow @phriends
    end
  else
    # @phriends is nil do smth for example
    flash[:notice] = "User with username #{params[:username]} is not found"
  end
end

更新:要小心,因为代码@phriends = User.find_by_username(params[:username])可以返回 nil,你可以得到nil.some_method。您可以添加检查@phriends是否为零

红宝石中的 PS nil 表示与布尔值的 false 相同

最新更新