【问题标题】:Rails: Having problems with follow and followed systemRails:关注和关注系统存在问题
【发布时间】:2012-02-14 03:34:52
【问题描述】:

这是我得到的错误

undefined method `followed_users?' for #<User:0x007fdadbf11e28>

提取的源代码(第 3 行附近):

1: <% unless current_user?(@user) %>
2:   <div id="follow_form">
3:   <% if current_user.followed_users?(@user) %>
4:     <%= render 'unfollow' %>
5:   <% else %>
6:     <%= render 'follow' %>

如果我删除问号,我会收到此错误

undefined method `model_name' for NilClass:Class

提取的源代码(第 1 行附近):

1: <%= form_for current_user.relationships.find_by_followed_id(@user),
2:              html: { method: :delete },
3:              remote: true do |f| %>
4:   <div class="actions"><%= f.submit "Unfollow" %></div>

我非常困惑,这是我的代码

用户模型

has_many :microposts
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?(other_user)
  relationships.find_by_followed_id(other_user.id)
end

def follow!(other_user)
  relationships.create!(followed_id: other_user.id)
end

def unfollow!(other_user)
  relationships.find_by_followed_id(other_user.id).destroy
end

关系模型

attr_accessible :followed_id

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

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

用户控制器

  def show
    @user = User.find(params[:id])
    @micropost = Micropost.new
    @microposts = @user.microposts.paginate(page: params[:page])
  end

关系控制器

  def create
    @user = User.find(params[:relationship][: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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 relationship


    【解决方案1】:

    您不应该在第 3 行使用 if current_user.following?(@user) 而不是 if current_user.followed_users?(@user)

    【讨论】:

    • 哇,谢谢,我正在学习脱轨教程,它是这样编码的!感谢您指出这一点
    • 干杯,我刚刚向 Michael Hartl 发送了一封电子邮件,让他修复它。不错的收获。
    • 感谢您的提醒。这是过度热心的搜索和替换的结果。它已修复。
    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多