我创建了两组不同的编码,假设允许用户关注(书签)另一个用户。例如,用户A跟随用户B,C和& D.用户A进入他们的收藏页面,它列出了他们所关注的所有用户(B,C& D)。这将是一个单向的方式。我创建的代码没有执行跟随用户的操作,所以我决定遵循导轨Twitter跟随概念。我得到一个“未初始化的常量RelationshipsController”。所以这些路线出了问题。
有人可以看看,也许可以指出出了什么问题吗?
在旁注中,这感觉就像很多简单的编码......即使我自己在没有遵循教程的情况下这样做。我只是希望用户能够将另一个用户页面URL添加为书签,将其保存到某些“收藏夹”页面(实际上是书签页面)并为其提供删除该书签的选项。我认为甚至不需要数据库。
路线:
resources :sessions, only: [:new, :create, :destroy]
resources :relationships, only: [:create, :destroy]
resources :users do
get 'settings', on: :member
end
用户模型:
has_many :notifications
has_many :users, dependent: :destroy
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
答案 0 :(得分:2)
想想它就像关系是多对多关联之间的连接表(即,用户可以关注许多人,并且许多人可以跟随用户)。你不应该需要关系路线。删除resources :relationships, only: [:create, :destroy]
。此外,请确保您已在关系表中迁移,如:
class CreateRelationships < ActiveRecord::Migration
def self.up
create_table :relationships do |t|
t.integer "follower_id"
t.integer "followed_id"
end
end
def self.down
drop_table :relationships
end
end
并创建了一个关系模型,如:
class Relationship <ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
end
答案 1 :(得分:2)
我走这条路:
resources :sessions, only: [:new, :create, :destroy]
resources :users do
get 'settings', on: :member
post 'follow', on: :member
post 'unfollow, on: :member
end
用户控制器中的:
def follow
friend = User.find params[:user_id]
current_user.follow! friend unless current_user.following? friend
redirect_to friend
end
def unfollow
friend = User.find params[:user_id]
current_user.unfollow! friend
redirect_to friend
end
并显示您要关注/取消关注的用户
<% if current_user.following? @user %>
<%= link_to 'Bookmark', follow_user_path(user_id: @user.id), method: :post %>
<% else %>
<%= link_to 'Remove Bookmark', unfollow_user_path(user_id: @user.id), method: :post %>
<% end %>