独自メソッドを用いてvalidateを行いたいと考えていましたがうまく行きません。ネット上にはhas_manyのバリデーションの仕方など掲載されておりましたがthroughを含めたものは見た限りありませんでした。
自分が開発しているアプリ内でフォローできる人数を8人以下にしたいです。そこでバリデーションを設置する事で8人以上の人をフォローをした時にエラーが表示されるようにしたいです。
以下のコードではバリデーションに引っかからず8人以上の人をフォローできるようになってしまいます。
よろしくお願いします。
やった事として、rails consoleを開き
first_following=Relationship.create(follower_id: "1", followed_id: "2") second_following=Relationship.create(follower_id: "1", followed_id: "3") third_following=Relationship.create(follower_id: "1", followed_id: "4") fourth_following=Relationship.create(follower_id: "1", followed_id: "5") fifth_following=Relationship.create(follower_id: "1", followed_id: "6") sixth_following=Relationship.create(follower_id: "1", followed_id: "7") seventh_following=Relationship.create(follower_id: "1", followed_id: "8") eighth_following=Relationship.create(follower_id: "1", followed_id: "9") ninth_following=Relationship.create(follower_id: "1", followed_id: "10")
上のコードを入力してレコードを作成し、9つともレコードが作成されました。エラーやレコードを作成できない
といったメッセージは表示されませんでした。
確認として,以下のコードを入力して9が出力され、9人フォローできていることも確認できました。
me=Account.find_by(id:"1") me.following.count
これでバリデーションに問題があるというのはわかったのですが実際にどこに問題があり、なぜバリデーションが機能せず、9人以上フォローすることができてしまうのかがよくわかりません。
account.rb
class Account < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower # ユーザーをフォローする def follow(other_account) following << other_account end # ユーザーをフォロー解除する def unfollow(other_account) active_relationships.find_by(followed_id: other_account.id).destroy end # 現在のユーザーがフォローしてたらtrueを返す def following?(other_account) following.include?(other_account) end end
relationship.rb
class Relationship < ApplicationRecord validates :follower_id, presence: true validates :followed_id, presence: true belongs_to :follower, class_name: "Account", optional: true belongs_to :followed, class_name: "Account", optional: true validate :check_following def check_following if Account.find(followed_id).following.count > 8 errors.add(:followed_id, "too much following") end end end
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。