私は一日中壁に頭をぶつけていましたが、おそらくかなり単純だと思うことをしようとしています。ユーザーがインタレストと呼ばれる別のモデルと (フォローまたはフォロー解除を介して) リレーションシップを持つことができるユーザー モデルがあります。
私のホームページでは、@user または current_user が「フォローしていない」すべての興味を表示したいと考えています。
私はコントローラーでこれのバリエーションを試してきました:
@interests = Interest.all.where(:current_user.following => nil)
"where" はデータベースの列を厳密に検索するように見え、私のリレーションシップ モデルは Interest テーブルに足跡を残さないため、これは明らかにうまくいきません。おかしなことに、ユーザーがフォローしているすべての興味を簡単に示すことができます。
@interests = current_user.following
「フォローしていない」メソッドまたはルートのモデルとコントローラーの新しいリソースとコードを作成する必要があるかもしれないと推測しています。しかし、Rails の初心者である私には、それがどのように見えるかわかりません。また、Stack や他の場所で役立つものを見つけることができないようです。
アップデート
要求に応じて、ここに User モデルがあります。
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :address, presence: true
has_secure_password
validates :password, length: { minimum: 6 }
has_many :relationships, :foreign_key => "follower_id",
:dependent => :destroy
has_many :following, :through => :relationships, :source => :followed
geocoded_by :address do |user,results|
if geo = results.first
user.city = geo.city
end
end
after_validation :geocode, :if => :address_changed?
def following?(interest)
relationships.find_by(followed_id: interest.id)
end
def follow!(interest)
relationships.create!(followed_id: interest.id)
end
def unfollow!(interest)
relationships.find_by(followed_id: interest.id).destroy!
end
そして、これが Interest モデルです。
class Interest < ActiveRecord::Base
has_many :relationships, :foreign_key => "followed_id",
:class_name => "relationship"
has_many :followers, :through => :reverse_relationships,
:source => :follower
has_many :followed_users, through: :relationships, source: :followed