error
1Started POST "/relationships" for ::1 at 2020-03-14 17:19:53 +0900 2Processing by RelationshipsController#create as HTML 3 Parameters: {"authenticity_token"=>"Sf3vgfyTOP3JKBT9ZzShGA0PqzBAXDhh8mH6m1jIMGXG7RlYrYZ0QhScuj0fNjIWKK5b/jdqJ/JMzQjj9ZQy+w==", "follow_id"=>"2", "commit"=>"Follow"} 4Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.0ms | Allocations: 1189) 5 6 7 8NoMethodError (undefined method `[]' for nil:NilClass): 9 10app/controllers/relationships_controller.rb:19:in `set_user'
relationshipscontroller
1class RelationshipsController < ApplicationController 2 before_action :set_user 3 4 def create 5 man = Man.find(params[:relationship][:follow_id]) 6 following = current_man.follow(man) 7 redirect_to "questions" 8 end 9 10 def destroy 11 man = Man.find(params[:relationship][:follow_id]) 12 following = current_man.unfollow(man) 13 redirect_to "questions" 14 end 15 16 private 17 18 def set_user 19 man = Man.find(params[:relationship][:follow_id]) 20 end 21 22end
views
1 <%= form_for(current_man.relationships.build) do |f| %> 2 <%= hidden_field_tag :follow_id, man.id %> 3 <%= f.submit 'Follow' %> 4 <% end %>
Manmodel
1class Man < ApplicationRecord 2 has_many :relationships 3 has_many :followings, through: :relationships, source: :follow 4 has_many :reverse_of_relationships, class_name: 'Relationship', foreign_key: 'follow_id' 5 has_many :followers, through: :reverse_of_relationships, source: :man 6 7 def follow(other_man) 8 unless self == other_man 9 self.relationships.find_or_create_by(follow_id: other_man.id) 10 end 11 end 12 13 def unfollow(other_man) 14 relationship = self.relationships.find_by(follow_id: other_man.id) 15 relationship.destroy if relationship 16 end 17 18 def following?(other_man) 19 self.followings.include?(other_man) 20 end 21end 22
relationshipsmodel
1class Relationship < ApplicationRecord 2 belongs_to :man 3 belongs_to :follow, class_name: 'Man' 4 5 validates :man_id, presence: true 6 validates :follow_id, presence: true 7end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。