質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 4

Ruby on Rails4はRubyによって書かれたオープンソースのウェブフレームワークです。 Ruby on Railsは「設定より規約」の原則に従っており、効率的に作業を行うために再開発を行う必要をなくしてくれます。

Q&A

解決済

1回答

573閲覧

rails4でのフォロー機能|gemはacts_as_followerを利用

yoshimitsu41

総合スコア36

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 4

Ruby on Rails4はRubyによって書かれたオープンソースのウェブフレームワークです。 Ruby on Railsは「設定より規約」の原則に従っており、効率的に作業を行うために再開発を行う必要をなくしてくれます。

0グッド

0クリップ

投稿2017/04/20 10:36

編集2017/04/20 10:50

Rails 4.2.6
ruby 2.3.1
mysql
で出会い系のWEBアプリケーションを勉強を兼ねてで構築しています。
rails初心者です。

###やりたいこと
ユーザーのshowアクションから
ユーザー同士がお気に入りボタンを押してお気に入りに追加できるようにしたい。

######ルーティング

ruby

1 Rails.application.routes.draw do 2 #devise_for :users 3 devise_for :users do 4 member do 5 get :follow 6 get :unfollow 7 end 8 end 9 root 'homes#index' #root_path 10 get 'flow' => 'flows#index' 11 get 'messages' => 'messages#index' 12 get 'profiles' => 'profiles#index' #プロフィールの一覧 13 get 'profiles/show' => 'profiles#show' #プロフィールの詳細内容 14 get 'profiles/new' => 'profiles#new' #プロフィールの登録画面 15 post 'profiles' => 'profiles#create' #プロフィールの登録画面 16 get 'profiles/:id/edit' => 'profiles#edit' 17 patch 'profiles/' => 'profiles#update' 18 get 'users/:id' => 'users#show' #mypageへのルーティング 19 get 'users' => 'users#index' #mypageへのルーティング 20 end

######Model
Userモデル(Deviseのgemを利用)

  • id
  • email
  • password
  • nickname

ruby

1class User < ActiveRecord::Base 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :trackable, :validatable 6 has_one :profile 7 acts_as_followable # フォロワー機能 8 acts_as_follower # フォロー機能 9end

Profileモデル

  • id
  • user_id
  • age
  • mytype
  • pref
  • text

ruby

1class Profile < ActiveRecord::Base 2 mount_uploader :image, ImageUploader 3 belongs_to :user 4end

Followモデル(acts_as_followerのgemを利用)

  • id
  • followable_id
  • followable_type
  • follower_id
  • follower_type

ruby

1class Follow < ActiveRecord::Base 2 3 extend ActsAsFollower::FollowerLib 4 extend ActsAsFollower::FollowScopes 5 6 # NOTE: Follows belong to the "followable" interface, and also to followers 7 belongs_to :followable, :polymorphic => true 8 belongs_to :follower, :polymorphic => true 9 10 def block! 11 self.update_attribute(:blocked, true) 12 end 13 14end 15

以上がmodel,db,各モデル.rbです。

ユーザーモデルとプロフィールモデルがアソシエーションで結ばれています。

######Controller
user_controller.rb

ruby

1class UsersController < ApplicationController 2 before_action :move_to_index, only: :index 3 4 def index 5 @user = User.all 6 end 7 8 def show 9 user = User.find(params[:id]) 10 @nickname = current_user.nickname 11 @email = current_user.email 12 @profile = user.profile 13 @friend = User.find(params[:id]) 14 ##以下はフォロー用 15 @me = current_user 16 @all = current_user.all_following 17 @user = User.find(params[:id]) 18 end 19 20 def follow 21 @user = User.find(params[:id]) 22 current_user.follow(@user) 23 redirect_to root_path 24 end 25 26 private 27 def move_to_index 28 redirect_to '/users/sign_in',:flash => {:alart => "ご利用にはログインが必要です。会員登録がまだの方は会員登録を行って下さい。"} unless user_signed_in? 29 end 30 31end

profiles_controller.rb

ruby

1class ProfilesController < ApplicationController 2 3 def index 4 end 5 6 def new 7 @nickname = current_user.nickname 8 @email = current_user.email 9 end 10 11 def create 12 Profile.create(birthday: profile_params[:birthday], bodytype: profile_params[:bodytype], mytype: profile_params[:mytype], pref: profile_params[:pref], text: profile_params[:text],image: profile_params[:image], user_id: current_user.id) 13 end 14 15 def show 16 @nickname = current_user.nickname 17 @email = current_user.email 18 end 19 20 def edit 21 @profile = User.find(params[:id]) 22 @nickname = current_user.nickname 23 @email = current_user.email 24 end 25 26 def update 27 profile = Profile.find_by(user_id: current_user.id) 28 profile.update(profile_params) 29 end 30 31 private 32 def profile_params 33 params.permit(:birthday, :bodytype, :mytype, :pref, :text, :image) 34 end 35 36end

です。

views/users/show.html.erbが下記です。
長いので該当の箇所だけ記載します。

ruby

1<% if current_user.following?(@user) %> 2お気に入り解除のボタン 3<% else %> 4お気に入りに登録する 5<% end %>

上記のようにする場合どのようにしてお気に入り登録、または解除を実装すればよいでしょうか?
ちなみにacts_as_followerの使い方は下記を参考にしました。
http://qiita.com/kurkuru/items/ad25569f64e74efdac56#%E3%81%8A%E3%82%8F%E3%82%8A%E3%81%AB
初心者のコードですのでめちゃくちゃだとは思いますがご教授お願い致します。

追記---------------------------------------------------
<%= link_to "Follow", @me.follow(@user) %>
を追加するとエラーになったり、リンクをクリックしていないのにフォロー機能が勝手に動くことが有るのですが原因もわかりません。。。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

色々間違っているのはわかりました。
今度から初心者マークをつけてください。

#簡単なwebアプリの仕組み

まず基本的なことから、webアプリは下記の4つから構成されます。

  • html5:HyperText Markup Languageインターネットの黎明期に学者が論文を共有するために作られた言語で、<tag></tag>で要素を管理する、それのversion5、デスクトップアプリに劣らないUIを備えた最新のもの
  • webフレームワーク:サーバーサイドに位置し、データ(DB)とユーザーからのアクションを結びつけブラウザ上にhtmlなどの結果を返す
  • javascript:webブラウザ上で動作する、軽量言語webブラウザ上で完結した動作をしたりwebフレームワークの動きを助けデータをやりとりしたりする
  • stylesheet:htmlにもデザインの機能はあるが、それを分離し、構造化したもの、通常、htmlのtagのclassやidを頼りにデザインを適用する。

web開発をしっかりやろうと思ったら最低限これら4つを勉強しないといけません。

でも、これらをしっかり勉強しなくても、かなりレベルの高いソフトが作れてしまい、知識があればさらに
細かいカスタマイズが可能なのがwebフレームワークたるRuby on Railsなのです。
#なぜ現在、期待した動作ができないか?(バグの説明)
以上を踏まえると、Ruby on Railsのコードが使えるのはサーバー上だけ、htmlを生成するところまでです。
なのでこれは

ruby

1<%= link_to "Follow", @me.follow(@user) %>

htmlを作成するときにRuby on Railsのコードとして@me.follow(@user)が実行され
フォローが成功したら成功を知らせるtrueが帰って
<a herf='/true'>Follow</a>というhtmlが生成されます。
これをいくら押してもtrueというページに行こうとするだけで(そんなページはない)
何も起こりません(html作成時にすでにフォローはされていますがw)
#じゃあ期待どうりにするにはどうすればいいのよ
やることは以下の3点です。
サーバー側でusers_controllerに、フォロー対象者を受け取ったら現在ログインしているユーザーでフォローする命令(プログラム)を書く。

ruby

1 def follow 2 @user = User.find(params[:user_id]) 3 current_user.follow(@user) 4 redirect_to user_path(@user) 5 end 6 def unfollow 7 @user = User.find(params[:user_id]) 8 current_user.stop_following(@user) 9 redirect_to user_path(@user) 10 end

※フォローした後に戻るページはユーザーの方がいいかなと思いuserに行くようになっています。

config/route.rbを編集してunfollowとfollowへの接続許可をだす。

ruby

1put 'users/flow/:user_id' => 'users#flow' 2put 'users/unflow/:user_id' => 'users#unflow'

サーバー側で押すとフォローしてくれるボタンを作る(この時必要な情報をボタンに渡す。)

ruby

1<%= link_to "Follow", {controller: :users,action: :follow,user_id: @user.id}, method: :put %> 2<%= link_to "UnFollow", {controller: :users,action: :unfollow,user_id: @user.id}, method: :put %>

※{controller: :users,action: :follow,user_id: @user.id}これはusers_controller.bのfollowというメソッド(命令に)user_idというパラメータに現在表示されているユーザーのidを渡して実行するという意味です。

最後に、生成されたボタンを押してください、うまく動くはずです。

投稿2017/04/22 08:22

編集2017/04/24 05:17
moke

総合スコア2241

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yoshimitsu41

2017/04/24 04:44

詳細なご回答ありがとうございます。 非常に勉強になりました。 更におっしゃるとおりコードを修正して動きました。 そもそもの基礎が把握出来ていないのだなぁと痛感した次第です。 ありがとうございました!
moke

2017/04/24 05:45

私も最初に全く同じようなコードを書いた覚えがあるのでw 過去の自分への回答のつもりで書きました。 基礎は重要ですが、プログラムも工業製品と同様、よりモジュール化 して、高度化し、アイデアをすぐ形にできるようになっています。 基礎を抑えるのも大事ですが、概念、仕組みを理解して、どんどんプロダクト を作る方が、学べることが多いと思います。 頑張ってください
yoshimitsu41

2017/04/24 06:57

なるほど、どんどん触って経験値を積みます!ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問