Ruby on railsで開発中です。
勉強のためにコミュニティ機能を作成しています。
現在やっている作業としてはコミュニティ機能の参加、退会機能を作成しています。
テーブルとしては中間テーブルとしてcommunity_participantテーブルがありまして、communityとuserが多対多の関係になっています。
参加は上手く動作しているようなのですが、退会(destroyアクション)が上手く動作していません。
原因としてはネストしたresourcesのidがnilとなり取得出来ていないことです。
routes.rbですが、communityの中だけで使用したいので
ruby
1resources :communities do 2 resources :community_participants, only: [:index, :create, :destroy, :update] 3end
としています。
また参加、退会機能に関する記述をしているcommunity_participants_controller.rbでは
ruby
1 before_action :set_community 2 before_action :set_community_participant, only: [:destroy] 3 4 def create 5 @community_partcipant = current_user.community_participants.build(community_id: params[:community_id]) 6 @community_participant.save! 7 redirect_to community_path(@community) 8 end 9 10 def destroy 11 @community_participant.destroy! 12 redirect_to community_path(@community) 13 end 14 15 def update 16 @community_participant = @community.community_participants.find(params[:id]) 17 @community_participant.update!(admin: true) 18 redirect_to community_community_participants_path(@community) 19 end 20 21 private 22 23 def set_community_participant 24 @community_participant = CommunityParticipant.find(params[:id]) 25 end 26 27 def set_community 28 @community = Community.find(params[:community_id]) 29 end
としています。
viewファイルでは
ruby
1<%= link_to 'コミュニティを退会する', community_community_participant_path(@community, @community_participant), method: :delete, class: "btn btn-danger" %>
と記述していますが、community_participantのidがnilとなってしまい上手く動作しません。
またエラー内容は以下となっています。
ruby
1No route matches {:action=>"update", :community_id=>"13", :controller=>"community_partcipants", :id=>nil}, missing required keys: [:id]
なぜcommunity_participantのidが取得出来ないのでしょうか?
以下追記しました。
communities_controller.rb
ruby
1 before_action :set_community, only: [:show, :edit, :update, :destroy] 2 3 def index 4 @communities = Community.order(id: :desc).page(params[:page]).per(3) 5 end 6 7 def new 8 @community = current_user.communities.build 9 end 10 11 def create 12 @community = current_user.communities.build(community_params) 13 if @community.save 14 redirect_to communities_path 15 else 16 render :new 17 end 18 end 19 20 def show 21 end 22 23 def edit 24 end 25 26 def update 27 if @community.update(community_params) 28 redirect_to @community 29 else 30 render :edit 31 end 32 end 33 34 def destroy 35 @community.destroy 36 redirect_to communities_path 37 end 38 39 private 40 41 def community_params 42 params.require(:community).permit(:name, :description) 43 end 44 45 def set_community 46 @community = Community.find(params[:id]) 47 end 48end
回答1件
あなたの回答
tips
プレビュー