0

私は一日中壁に頭をぶつけていましたが、おそらくかなり単純だと思うことをしようとしています。ユーザーがインタレストと呼ばれる別のモデルと (フォローまたはフォロー解除を介して) リレーションシップを持つことができるユーザー モデルがあります。

私のホームページでは、@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
4

3 に答える 3

1

@Aymanの答えへのコメント:

あなたの興味モデルがどのように見えるか、または次のリターンがどうなるかはわかりませんが、次のようなものがうまくいくと思います:

Interest.where('interest_id が (?) にありません', current_user.following.map(&:id))

メソッドでこのクエリを使用することができますpluck:

Interest.where("interest_id NOT IN (?)", current_user.following.pluck(:id))
于 2013-09-12T08:48:43.900 に答える
1

Interestモデルがどのように見えるか、または何が返されるかはわかりませんが、次のようなものが機能followingすると思います。

Interest.where('interest_id not in (?)', current_user.following.map(&:id))
于 2013-09-12T04:05:51.193 に答える