0

ユーザーが別のユーザーをフォロー (ブックマーク) できるようにするための 2 つの異なるコーディング セットを作成しました。たとえば、ユーザー A がユーザー B、C、および D をフォローしているとします。ユーザー A がお気に入りページに移動すると、フォローしているすべてのユーザー (B、C、D) が一覧表示されます。これは一方通行になります。私が作成したコードは、ユーザーをフォローするアクションを実行しなかったため、railstutorial の 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
4

2 に答える 2

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 %>
于 2013-08-28T21:26:28.613 に答える