1# == Schema Information2#3# Table name: users4#5# id :integer not null, primary key6# name :string7# created_at :datetime not null8# updated_at :datetime not null9# friend :integer10#1112classUser<ApplicationRecord13 scope :friends,->(id){ where('friend = :id', id: id)}14 scope :not_me,->(id){ where('id != :id', id: id)}15 scope :others,->(id){ where('id not in (?)', friends(id).pluck(:id)+[id])}16end
ruby
1User.others(current_user.id)
ruby
1definit_actors2@me=User.create(name:'me')3 _friends =4Array.new(3){|i|User.create(name:"friends No.#{i}", friend:@me.id)}5 _others =6Array.new(3){|i|User.create(name:"others No.#{i}")}7end89RSpec.describe User, type::modeldo10 context 'scope methods'do11 subject {User}12 it { is_expected.to respond_to :friends}13 it { is_expected.to respond_to :not_me}14 it { is_expected.to respond_to :others}15end1617 context 'search friends'do18 before { init_actors }1920 it 'has 3 friends'do21 expect(User.friends(@me.id).size).to eq 322end2324 it 'name includes "friends"'do25User.friends(@me.id).eachdo|user|26 expect(user.name).to include'friends'27end28end2930 after {User.destroy_all }31end3233 context 'search not me'do34 before { init_actors }3536 it 'has 6 records'do37 expect(User.not_me(@me.id).size).to eq 638end3940 it 'name not includes "me"'do41User.friends(@me.id).eachdo|user|42 expect(user.name).to_not include'me'43end44end4546 after {User.destroy_all }47end4849 context 'search not friends and not me'do50 before { init_actors }5152 it 'has 3 records'do53 expect(User.others(@me.id).to_a.size).to eq 354end5556 it 'name includes "others"'do57User.others(@me.id).eachdo|user|58 expect(user.name).to include'others'59end60end6162 after {User.destroy_all }63end64end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。