Rails 3.2,推特应用
解决方案参见:由于 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_id。这也是他们的追随者/编辑ID。
奔奔可以输入“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
你认为什么会起作用?