Rails:跟随和遵循系统有问题

时间:2012-02-14 03:34:53

标签: 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

用户控制器

  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

1 个答案:

答案 0 :(得分:3)

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