Rails 3.2,Twitter App
解决方案:Can't unfollow user because of Postgres
目标是一个类似的形式。
username => User => User.id => followed_id => following? => New or Destroy Relationship
这是我现在必须关注的推特用户。
views/users/buddies.html.erb
<%= form_for @relationship do |f| %>
<%= f.text_field :followed_id %>
<%= f.submit "Add" %>
users_controller.rb
def buddies
@relationship =Relationship.new(params[:followed_id])
relationships_controller.rb
def create
@relationship = Relationship.new(params[:relationship])
@relationship.follower_id = current_user.id
if @relationship.save
redirect_to buddies_path, notice: "Phriend added"
else
flash[:error] = "Phriend not added";
redirect_to buddies_path
end
relationship.rb
class Relationship < ActiveRecord::Base
attr_accessible :followed_id, :follower_id
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :followed_id, presence: true
validates :follower_id, presence: true
user.rb
class User < ActiveRecord::Base
has_many :follower_relationships, class_name: "Relationship", foreign_key: "followed_id"
has_many :followed_relationships, class_name: "Relationship", foreign_key: "follower_id"
has_many :followers, through: :follower_relationships
has_many :followeds, through: :followed_relationships
那样做的是:
我有4个用户:1:benben,2:nicknick,3:stevesteve,4:petepete
这些是他们的user_ids。这也是他们的追随者/编辑。
Benben可以键入“2”,然后按“nicknick”等。
我想要一个系统,我可以通过提交用户名来关注和取消关注。
所以我想象了这样......
users_controller.rb
@user = User.find(params[:username])
if @user
if current_user.following? @user.id
Relationship.new(params[:followed_id])
else
Relationship.destroy(params[:followed_id])
end
end
user.rb
def following? user
self.followeds.include? user
end
您认为有什么用?
答案 0 :(得分:0)
您所要做的就是确保获得要与之关联的正确用户。
如果您按ID或按名称搜索,则无关紧要。如果您拥有该用户的活动记录,则只需连接对象即可轻松关联。
#find by whatever params float your boat
@user = User.find(params[:user])
#add the user to the list of followers
current_user.followers << @user
current_user.save
#or you could delete
@lame_follower = current_user.followers.find(1)
@lame_follower.destroy