前提・実現したいこと
Twitterクローンの作成をしております。
フォローおよびアンフォロー機能を作成し、試しにコンソールにて下記フォローの指示をしたところ、エラーが出てつまずいてしまいました。
お知恵を拝借できますと大変助かります。
User.all # 存在するUserの確認
user1 = User.find(1) # followするUserの取得
user2 = User.find(2) # followされるUserの取得
発生している問題・エラーメッセージ
Traceback (most recent call last): 11: from bin/rails:9:in `<main>' 10: from bin/rails:9:in `require' 9: from /home/ec2-user/.rvm/gems/ruby-2.6.0/gems/railties-5.0.7.2/lib/rails/commands.rb:18:in `<top (required)>' 8: from /home/ec2-user/.rvm/gems/ruby-2.6.0/gems/railties-5.0.7.2/lib/rails/commands/commands_tasks.rb:49:in `run_command!' 7: from /home/ec2-user/.rvm/gems/ruby-2.6.0/gems/railties-5.0.7.2/lib/rails/commands/commands_tasks.rb:78:in `console' 6: from /home/ec2-user/.rvm/gems/ruby-2.6.0/gems/railties-5.0.7.2/lib/rails/commands/console_helper.rb:9:in `start' 5: from /home/ec2-user/.rvm/gems/ruby-2.6.0/gems/railties-5.0.7.2/lib/rails/commands/console.rb:65:in `start' 4: from (irb):12 3: from (irb):12:in `rescue in irb_binding' 2: from /home/ec2-user/environment/microposts/app/models/user.rb:17:in `follow' 1: from /home/ec2-user/.rvm/gems/ruby-2.6.0/gems/activemodel-5.0.7.2/lib/active_model/attribute_methods.rb:433:in `method_missing' NoMethodError (undefined method `relationships' for #<User:0x00000000040f0ce0>)
該当のソースコード
【relationship.rb】 class Relationship < ApplicationRecord belongs_to :user belongs_to :follow, class_name: 'User' end 【user.rb】 class User < ApplicationRecord before_save { self.email.downcase! } validates :name, presence: true, length: { maximum: 50 } validates :email, presence: true, length: { maximum: 255 }, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+.[a-z]+\z/i }, uniqueness: { case_sensitive: false } has_secure_password has_many :microposts has_many :relationships has_many :followings, through: :relationships, source: :follow has_many :reverses_of_relationship, class_name: 'Relationship', foreign_key: 'follow_id' has_many :followers, through: :reverses_of_relationship, source: :user def follow(other_user) unless self == other_user self.relationships.find_or_create_by(follow_id: other_user.id) end end def unfollow(other_user) relationship = self.relationships.find_by(follow_id: other_user.id) relationship.destroy if relationship end def following?(other_user) self.followings.include?(other_user) end end
回答1件
あなたの回答
tips
プレビュー