我整天都在用头撞墙,试图做一些我觉得可能很简单的事情。我有一个用户模型,其中用户可以与另一个称为兴趣的模型建立关系(通过关注或取消关注)。
在我的主页上,我想显示 @user 或 current_user 未“关注”的所有兴趣。
我一直在我的控制器中尝试这种变化:
@interests = Interest.all.where(:current_user.following => nil)
显然,这是行不通的,因为“where”似乎严格搜索数据库列,而且我的关系模型不会在 Interest 表中留下任何足迹。有趣的是,我可以通过一个简单的方法轻松显示我的用户关注的所有兴趣
@interests = current_user.following
我猜我可能不得不为我的模型和控制器编写新的资源和代码,以实现“不遵循”的方法或路线。但是作为 Rails 的新手,我不知道那会是什么样子,而且我似乎无法在 Stack 或其他地方找到任何帮助。
更新
根据要求,这是用户模型:
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
这是兴趣模型:
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