2013-08-28 37 views
0

我已經創建了兩種不同的編碼集,假設允許用戶關注(書籤)另一個用戶。例如,用戶A跟隨用戶B,C,& D.用戶A進入他們的收藏夾頁面並且列出他們正在關注的所有用戶(B,C & D)。這將是一種單向的方式。我創建的代碼沒有執行跟隨用戶的操作,所以我決定遵循概念上的railstutorial Twitter。我得到一個「未初始化的常量RelationshipsController」。所以路線出了問題。設置,以便用戶可以關注(書籤)其他用戶

有人可以看看,也許指出什麼是錯的?

在一個側面說明,這感覺就像很多編碼的東西這麼簡單...即使當我自己做這個沒有遵循教程。我只是希望用戶能夠爲另一個用戶頁面網址添加書籤,並將其保存到某個收藏夾頁面(實質上是一個書籤頁面),併爲他們提供刪除該書籤的選項。我認爲這個數據庫甚至不需要。

路線:

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

我需要添加relationships_controller才能使其工作。 –

回答

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 

a nd顯示要關注/取消關注的用戶時

<% 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 %> 
+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 
+0

謝謝您嘗試協助。 –

相關問題