我有一个用户模型,可以创建关系,让追随者和关注其他人,我从rails教程学到的所有东西都很棒。有一件事是我试图通过添加能够看到其他人的追随者并能够拥有追随/追随按钮选项的选项来进行下一步。显然,代码已经到位了,它把所有的东西放在应该是的位置(追随者小配置文件,按钮等),但是当我点击按钮时,它只会跟随我自己,或者放弃自己而不是我选择关注的特定人物,我能解决这个问题吗?任何帮助深表感谢!Rails:关注/关注关系按钮
这是以下和追随者页面的代码:
<div id='ContentContainer'>
<div class='ContentLeft'>
<% if @users.any? %>
<%= render @users %>
<%= will_paginate @users %>
<% end %>
</div>
</div>
这导致呈现用户模板,其中包括该
<% unless current_user?(@user) %>
<div id="follow_form_small">
<% if current_user.followed_users?(@user) %>
<%= render 'unfollow_small' %>
<% else %>
<%= render 'follow_small' %>
<% end %>
</div>
<% end %>
然后后续的分别取消关注形式
<%= form_for current_user.relationships.build(followed_id: @user.id),
remote: true do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", :class => 'FollowButton_small' %>
<% end %>
<%= form_for current_user.relationships.find_by_followed_id(@user),
html: { method: :delete },
remote: true do |f| %>
<%= f.submit "Unfollow", :class => 'UnFollowButton_small' %>
<% end %>
关系控制器
class RelationshipsController < ApplicationController
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
end
关系模型
class Relationship < ActiveRecord::Base
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
end
用户模型这也被加入到它
def following?(other_user)
relationships.find_by_followed_id(other_user.id)
end
def followed_users?(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
按照表格
<% unless current_user?(@user) %>
<div id="follow_form_small">
<% if current_user.followed_users?(@user) %>
<%= render 'unfollow_small' %>
<% else %>
<%= render 'follow_small' %>
<% end %>
</div>
<% end %>
当前用户
private
def current_user
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end
helper_method :current_user
新编辑
class Relationship < ActiveRecord::Base
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
validate :not_following_himself
def not_following_himself
errors.add :followed_id,
if followed_id == follower_id
end
end
你能告诉你关系控制器的创建方法吗?可能会有一些错误。 – Naveed 2012-02-16 07:16:54
@Naveed刚添加它 – Kellogs 2012-02-16 07:19:28
一切看起来文件把调试器放在创建方法,看看是什么在params。 – Naveed 2012-02-16 07:49:42