前提
学習開始5ヶ月の初心者です。
現在、RailsにてStripeを使用し、サブスクリプション機能の実装中です。
決済機能は実装完了したのですが、ユーザーへサブスクを登録済み、未登録で登録ページへの条件分岐をさせたく、if文で記述をしておりましたが、下記エラーが発生いたしました。
NoMethodError in Gyms#index Showing /Users/aberyou/projects/gym_search/app/views/layouts/_header.html.erb where line #55 raised: undefined method `user_id' for nil:NilClass
実現したいこと
ユーザーがサブスク登録済みであれば有償版へのボタンは表示させない、未登録であれば表示させる。
該当のソースコード
下記をレンダリングしてindex.html.erbのヘッダーとして表示させています。
_header
1省略 2<ul class="nav nav-pills"> 3 <li class="nav-item"> 4 <%= link_to current_user.name, edit_user_registration_path, class: "nav-link active" %> 5 </li> 6 <% if @team.user_id == current_user.id %> ←ここでユーザーが登録していれば何も表示させない! 7 <% else %> 8 <li class="nav-item"> 9 <%= link_to "有償版へグレードアップ", new_team_path, class:"nav-link" %> 10 </li> 11 <% end %> 12 <li class="nav-item"> 13 <%= link_to "ログアウト", destroy_user_session_path, method: :delete, class:"nav-link" %> 14 </li> 15 </ul> 16省略
Gymscontroller
1class GymsController < ApplicationController 2 def index 3 @gyms = Gym.all 4 end 5 6 def show 7 @gym = Gym.find(params[:id]) 8 gon.lat = @gym.lat.to_f 9 gon.lng = @gym.lng.to_f 10 end 11 12 def search 13 @gyms = Gym.search(params[:keyword]) 14 end 15end
Teamcontroller
1class TeamsController < ApplicationController 2 def new 3 @user = current_user 4 @team = Team.find_by(user_id: @user.id) 5 end 6 7 def create 8 @team = Team.new(user_id: current_user.id) 9 customer = Stripe::Customer.create({ 10 source: params[:stripeToken] 11 }) 12 subscription = Stripe::Subscription.create({ 13 customer: customer.id, 14 plan: "price_1LNWJtCUmfQ7g7y2yJZWEbuo" 15 }) 16 @team.plan_id = "price_1LNWJtCUmfQ7g7y2yJZWEbuo" 17 @team.customer_id = customer.id 18 @team.stripe_subscription_id = subscription.id 19 @team.active_until = Time.zone.at(subscription.current_period_end) 20 if @team.save 21 flash[:success] = "成功しました" 22 redirect_to root_url 23 else 24 render 'new' 25 end 26 end 27 28 def destroy 29 @team = Team.find_by(user_id: current_user.id) 30 deleting_stripe_subscription = Stripe::Subscription.retrieve(@team.stripe_subscription_id) 31 if current_user.unsubscribe 32 deleting_stripe_subscription.delete 33 flash[:notice] = "解約に成功しました" 34 redirect_to root_url 35 else 36 render 'new' 37 end 38 end 39end
試したこと
<% if @team.user_id == current_user.id %>
上記の記述にて@team内にuser_idがないというエラーかと認識しております。(間違っていたすみません)
「インスタンス変数が良くない?」と思い、team.user_idにしても見ましたが、変わらずでした。
何度も見受けしているエラーなので初歩的な部分かと存じますが、貴重なご意見賜れませんでしょうか。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/07/20 12:44 編集
2022/07/20 13:39
2022/07/25 03:41
2022/07/25 09:22