ruby-on-rails - rails : Having problems with follow and followed system

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

这是我得到的错误

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

用户 Controller

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

关系 Controller

  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

最佳答案

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

关于ruby-on-rails - rails : Having problems with follow and followed system,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9271340/

相关文章:

ruby-on-rails - 如何删除 Ruby on Rails 中散列中的重复项?

ruby-on-rails - Ajax page.replace_html 部分在 Rails 中的问题

ruby-on-rails - Ruby on Rails 在 URL 中传递参数

ruby-on-rails - 在 Rails/PostGreSQL 中对大表进行分析

ruby - 如何将变量传递给 ruby​​ 中的 system() 调用?

ruby - 如何将 Thor::Group 注册为带参数的子命令

ruby-on-rails - 在寻找不存在的 key 时,还有其他人遇到 aws-s3 超时问题吗? S3 对象存在?和 S3 Object.request( :head, ..)

python - 有人知道如何使用 Ruby 或 Python 在屏幕上显示内容(覆盖任何窗口)吗?

ruby-on-rails-3 - 在 Rails 3 应用程序中本地使用 Heroku Postgres 数据库

ruby-on-rails - 在哪里放置 Rails Controller 的 Ruby 辅助方法?