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

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

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

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

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails 4

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

Q&A

1回答

4467閲覧

[Rails]before_actionが効かない

s_diff

総合スコア107

Ruby

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

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails 4

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

0グッド

0クリップ

投稿2019/06/04 08:11

編集2019/06/27 00:41

管理画面のログイン機能を実装しています。

コードは以下です。

  1. PhotographersControllerでsession[:p_id]を取得し、ログインしてphotographer/distribution_controller.rbのscheduleメソッドに飛ばします。
  2. Photographer::DistributionsControllerはPhotographer::ApplicationControllerを受け継いでいて、Photographer::ApplicationController内にcurrent_photographerメソッドを記述しています。
  3. current_photographerメソッドをPhotographer::DistributionsController内でbefore_actionで記述しています。

routes.rb

ruby

1namespace :photographer do 2 resources :distributions do 3 get 'schedule' 4 end 5end 6 7get 'photographer_login' => 'photographers#login_form' 8post 'photographer_login' => 'photographers#login' 9get 'photographer_logout' => 'photographers#logout' 10 11get '*path', controller: 'application', action: 'handle_404'

controllers/photographers_controller.rb

ruby

1class PhotographersController < ApplicationController 2 3 def login_form 4 return redirect_to schedule_photographer_distribution_path(session[:p_id]) if session[:p_id] 5 end 6 7 def login 8 @photographer = Photographer.find_by(email: params[:email]) 9 if @photographer && @photographer.authenticate(params[:password]) 10 forwarding_url = session[:previous] 11 reset_session 12 session[:p_id] = @photographer.id 13 flash[:notice] = "ログインしました" 14 return redirect_to (forwarding_url || photographer_distributions_url) 15 else 16 flash.now[:alert] = "エラーが発生しました" 17 @email = params[:email] 18 @password = params[:password] 19 return render :login_form 20 end 21 end 22 23 def logout 24 reset_session 25 flash[:notice] = "ログアウトしました" 26 redirect_to("/photographer_login") 27 end 28end 29

controllers/photographer/application.controller.rb

ruby

1class Photographer::ApplicationController < ApplicationController 2 layout 'photographers_distribution' 3 before_action :current_photographer 4 rescue_from ActionController::RoutingError, with: :handle_404 5 6 def current_photographer 7 unless session[:p_id] 8 reset_session 9 store_location 10 return redirect_to photographer_login_path 11 end 12 @current_photographer = Photographer.find(session[:p_id]) 13 end 14 15 def check_user_agent_for_mobile 16 if request.from_ipad? 17 request.variant = :pc 18 elsif request.from_smartphone? 19 request.variant = :mobile 20 else 21 request.variant = :pc 22 end 23 end 24 25 def handle_404 26 respond_to do |format| 27 format.html { 28 return render template: 'errors/error_404', status: 404, layout: false, content_type: 'text/html' 29 } 30 format.all { 31 return head :not_found 32 } 33 end 34 end 35 36 private 37 def store_location(url = nil) 38 session[:previous] = request.url if request.get? 39 session[:previous] = url unless url.nil? 40 end 41end

photographer/distribution_controller.rb

ruby

1class Photographer::DistributionsController < Photographer::ApplicationController 2 before_action :check_user_agent_for_mobile 3 4 def index 5 @dists = PhotographersDistribution.where(display_flg: true).order(id: :desc) 6 end 7end 8

###ログ
check_user_agent_for_mobileメソッドとcurrent_photographerメソッドが呼ばれない場合のログ

I, [2019-06-21T14:15:36.562217 #61286] INFO -- : Started POST "/photographer_login" for 127.0.0.1 at 2019-06-21 14:15:36 +0900 I, [2019-06-21T14:15:36.580546 #61286] INFO -- : Processing by PhotographersController#login as HTML I, [2019-06-21T14:15:36.580672 #61286] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"XEHv55kFs+XFYq5I3ZH+xE/6CSJLSd2PNK/UTOeP+C3EF0j4VIFZ4Ii4eXMQDihLZQ+Z6P3rOY94lp+8TBzJDA==", "email"=>"admin@example.com", "password"=>"[FILTERED]"} D, [2019-06-21T14:15:36.593618 #61286] DEBUG -- : Photographer Load (3.1ms) SELECT `photographers`.* FROM `photographers` WHERE `photographers`.`email` = 'admin@example.com' LIMIT 1 I, [2019-06-21T14:15:36.658521 #61286] INFO -- : Redirected to http://localhost:3000/photographer/distributions I, [2019-06-21T14:15:36.658770 #61286] INFO -- : Completed 302 Found in 78ms (ActiveRecord: 8.6ms I, [2019-06-21T14:15:36.664076 #61286] INFO -- : Started GET "/photographer/distributions" for 127.0.0.1 at 2019-06-21 14:15:36 +0900 /Users/livesearch/Desktop/job/contents-store/app/controllers/photographer/distributions_controller.rb:1: warning: toplevel constant ApplicationController referenced by Photographer::ApplicationController I, [2019-06-21T14:15:36.691243 #61286] INFO -- : Processing by Photographer::DistributionsController#index as HTML D, [2019-06-21T14:15:36.709322 #61286] DEBUG -- : PhotographersDistribution Load (2.8ms) SELECT `photographers_distributions`.* FROM `photographers_distributions` WHERE `photographers_distributions`.`status_id` = 2 ORDER BY `photographers_distributions`.`id` DESC D, [2019-06-21T14:15:36.757196 #61286] DEBUG -- : Request Load (3.7ms) SELECT `requests`.* FROM `requests` WHERE `requests`.`id` = 121 LIMIT 1 I, [2019-06-21T14:15:36.839963 #61286] INFO -- : Completed 500 Internal Server Error in 148ms (ActiveRecord: 17.8ms) F, [2019-06-21T14:15:36.847954 #61286] FATAL -- : NoMethodError - undefined method `latitude' for nil:NilClass: app/views/photographer/distributions/index.html+mobile.erb:31:in `_app_views_photographer_distributions_index_html_mobile_erb__30980350848312437_70305103253380' D, [2019-06-21T14:15:37.026341 #61286] DEBUG -- : D, [2019-06-21T14:15:37.026457 #61286] DEBUG -- : I, [2019-06-21T14:15:37.026764 #61286] INFO -- : Started POST "/__better_errors/d07df247e6337ae9/variables" for 127.0.0.1 at 2019-06-21 14:15:37 +0900

photographers/distributions/index.html+mobile.erb

ruby

1 <script type="text/javascript"> 2 function allMap() { 3 handler = Gmaps.build('Google'); 4 handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){ 5 markers = handler.addMarkers(<%=raw @hash.to_json %>); 6 handler.bounds.extendWith(markers); 7 handler.fitMapToBounds(); 8 handler.getMap().setZoom(12); 9 google.maps.event.trigger(map,'resize'); 10 handler.map.centerOn([<%= @current_photographer.latitude %>,<%= @current_photographer.longitude %>]); ⬅この行で@current_photographernilだと言われる。 // 11 }); 12 } 13 </script>

current_photographerメソッドが呼ばれる場合のログ(class PhotographersController内のコードにスペースを入れたりすると、呼ばれる)

D, [2019-06-21T14:19:45.543022 #61286] DEBUG -- : D, [2019-06-21T14:19:45.544650 #61286] DEBUG -- : I, [2019-06-21T14:19:45.545663 #61286] INFO -- : Started POST "/__better_errors/c1bb543e52e1faf2/variables" for 127.0.0.1 at 2019-06-21 14:19:45 +0900 D, [2019-06-21T14:19:51.656377 #61286] DEBUG -- : D, [2019-06-21T14:19:51.656729 #61286] DEBUG -- : I, [2019-06-21T14:19:51.656884 #61286] INFO -- : Started GET "/photographer/distributions" for 127.0.0.1 at 2019-06-21 14:19:51 +0900 I, [2019-06-21T14:19:52.545131 #61286] INFO -- : Processing by Photographer::DistributionsController#index as HTML D, [2019-06-21T14:19:52.589319 #61286] DEBUG -- : Photographer Load (0.9ms) SELECT `photographers`.* FROM `photographers` WHERE `photographers`.`id` = 1 LIMIT 1 D, [2019-06-21T14:19:52.608170 #61286] DEBUG -- : PhotographersDistribution Load (0.3ms) SELECT `photographers_distributions`.* FROM `photographers_distributions` WHERE `photographers_distributions`.`status_id` = 2 ORDER BY `photographers_distributions`.`id` DESC D, [2019-06-21T14:19:52.636882 #61286] DEBUG -- : Request Load (1.1ms) SELECT `requests`.* FROM `requests` WHERE `requests`.`id` = 121 LIMIT 1 I, [2019-06-21T14:19:52.665693 #61286] INFO -- : Rendered layouts/_infowindow_photographer.html.erb (0.6ms) D, [2019-06-21T14:19:52.666663 #61286] DEBUG -- : Request Load (0.3ms) SELECT `requests`.* FROM `requests` WHERE `requests`.`id` = 119 LIMIT 1 I, [2019-06-21T14:19:52.673087 #61286] INFO -- : Rendered layouts/_infowindow_photographer.html.erb (0.5ms) D, [2019-06-21T14:19:52.675698 #61286] DEBUG -- : Request Load (0.7ms) SELECT `requests`.* FROM `requests` WHERE `requests`.`id` = 135 LIMIT 1 I, [2019-06-21T14:19:52.680291 #61286] INFO -- : Rendered layouts/_infowindow_photographer.html.erb (0.4ms) I, [2019-06-21T14:19:52.691623 #61286] INFO -- : Rendered photographer/distributions/index.html+mobile.erb within layouts/photographers_distribution (1.3ms) I, [2019-06-21T14:19:52.843714 #61286] INFO -- : Completed 200 OK in 298ms (Views: 163.1ms | ActiveRecord: 27.2ms)

###問題点
ログインしてビューにリダイレクトした際、
class Photographer::ApplicationControllerのcurrent_photographerメソッドが呼ばれません。

ページを更新しても変化はないのですが、photographer::DistributionsControllerのコードの一部を変更(スペースを入れるなど)すると、schedule.html+mobile.erbが呼ばれます。

実現したいこと

ログインした際にclass Photographer::ApplicationControllerのcurrent_photographerメソッドが呼ばれるようにしたいです。

何かご教示いただけることがあれば、なにとぞよろしくお願いいたします。

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

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

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

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

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

Mugheart

2019/06/19 01:11

こんにちは、ログをさらっと見てみたんですが、以下部分 Completed 500 Internal Server Error in 10ms (ActiveRecord: 1.9ms) F, [2019-06-14T09:04:44.173953 #29691] FATAL -- : NoMethodError - undefined method id' for nil:NilClass: app/controllers/photographer/distributions_controller.rb:45:in schedule' エラーが起きているようなので、まずはそこから直すべきではないでしょうか?
s_diff

2019/06/21 01:31

Mugheartさん、ありがとうございます。 そのとおりなのですが、そのエラーが起こる理由がわからないのです。 photographer/distributions_controller.rbのscheduleメソッド内の @current_photographer.idで、そのエラーが起こっています。 ですが、photographer/distributions_controller.rbはPhotographer::ApplicationControllerクラスを継承していて、この継承元クラスの中でbefore_action :current_photographerを実行しているので、このエラーがなぜ起こっているのかわからないのです。
Mugheart

2019/06/21 01:59

Photographer::DistributionsController#scheduleへのパスは photographer_distribution_schedule_path だと思うのですが リダイレクトしている先は photographer_schedule_url(session[:p_id]) になってます。 本来不要なはずの引数まで付いているのが気になりますね。 なので NoMethodError - undefined method id' for nil:NilClass が実際に起きている箇所は別のところのような気がしています。 app/controllers/photographer/distributions_controller.rb:45 とあるようにdistributions_controller.rbの45行目なのですがそこに間違いないでしょうか...?
s_diff

2019/06/21 06:03 編集

リダイレクト先の記述ミスでした。 photographer_distributions_urlになおしております。 このコードでログインしたところ、photographer/distributions/index.html+mobile.erb内で@current_photographerがないというエラーが出ています。
Mugheart

2019/06/21 04:02

「挙動がおかしい」部分は解決したということでよろしいでしょうか。 > photographer/distributions/index.html+mobile.erb内で > @current_photographerがないというエラーが出ています。 これに関してはエラーメッセージやコードがないのでコメントできません。 質問内容もごちゃごちゃしてきているので一旦質問を整理することをお勧めします。
s_diff

2019/06/21 06:04 編集

ご指摘ありがとうございます。 質問を整理いたしました。 モバイルページに飛ばないエラーをでなくなりましたが、@current_photographerがないエラーは未だに続いています。
s_diff

2019/06/21 06:47 編集

とても不思議なのですが、このエラーはローカルでは起きるのですが、AWSのEC2で構築しているstaging環境では起きません。
Mugheart

2019/06/21 06:50

ログが読みづらいので「```」で囲ってくれると助かります
s_diff

2019/06/21 06:52

ご指摘ありがとうございます。 修正しました。
Mugheart

2019/06/21 07:09

before_actionを通っていないというのは確実に検証しましたか? 具体的にはブレイクポイントを作って止める、とかです。
s_diff

2019/06/21 09:15

Photographer::ApplicationControllerのcurrent_photographerメソッド内の最後にブレイクポイントを作ったところ、 メソッド内で止まったのでbefore_actionが通っているのだと思います。 また、ブレイクポイントでインスタンスの@current_photographerにはレコードが存在しました。 なぜ@current_photographerがPhotographer::DistributionsControllerに渡っていかないのでしょうか?
Mugheart

2019/06/22 07:59

原因かどうかわかりませんが def login_form return redirect_to photographer_schedule_path(session[:p_id]) if session[:p_id] end この部分をはじめ、リダイレクト先がおかしなところがあります。 その辺りが影響しているのではないでしょうか。
s_diff

2019/06/27 00:40

Mugheartさん、返信が遅れて大変申し訳ありません! リダイレクト先の記述を書き間違えておりました。 正しくはschedule_photographer_distribution_pathです。すでに自分の手元では修正しておりました。 質問文の方も修正しております。
guest

回答1

0

問題はbefore_actionでcheck_user_agent_for_mobileが実行されないことですか?
それともvariantが効いていないことですか?

操作をした内容とログをもらえれば詳細な回答ができると思いますが、routesが独特なのでコードだけでは判断できないです。

投稿2019/06/10 17:36

odyu

総合スコア548

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

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

s_diff

2019/06/14 00:21

odyu様、ご回答ありがとうございます。 ログを追記しました。 何卒よろしくお願いいたします。
odyu

2019/06/14 01:11

全体的に少し直した方がいいところがあります。 例えば @current_photographer = Photographer.find_by(id: session[:p_id]) curret_photographer内の上記。 インスタンス変数がなくてもいいなら良いのですが、ろぐを見るとnilクラスでエラーになってますね。 ないといけないなら、ちゃんとfindメソッドを使って404エラーにしましょう。
s_diff

2019/06/14 02:46

ご指摘ありがとうございます。 ご指摘の通り修正いたしました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問