【问题标题】:Rails Search Self Referential RelationshipRails 搜索自引用关系
【发布时间】:2013-02-15 16:51:49
【问题描述】:

我试图让用户通过电子邮件地址搜索他们自己的朋友。我想做类似的事情:

current_user.search('test@fake.com')

并让它返回具有该电子邮件地址的当前用户朋友数组。

所以我在我的用户模型上建立了一个非常基本的友谊关系

user.rb
has_many :friendships
has_many :friends, through: :friendships, source: :friend
has_many :inverse_friendships, class_name: 'Friendship', foreign_key: 'friend_id'
has_many :inverse_friends, through: :inverse_friendships, source: :user

friendship.rb
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
belongs_to :user

我想在我的用户模型上设置一个方法,可以通过电子邮件地址搜索他们的朋友。效果不是很好

def search(query)
  conditions = ['friends.user_id = ? AND email LIKE ? ', self.id, "%#{query}%"]
  User.includes(:friends).where(conditions)
end

我想我只是不确定如何在此处格式化我的活动记录查询/SQL,因为我正在尝试搜索自引用模型的关系。有人有什么想法吗?

谢谢!

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 rails-activerecord


    【解决方案1】:

    Digital Cake 正朝着正确的方向发展,但并不完全正确。范围是用户的方法,而不是用户。你需要的是:

    def followers_by_email(email) 
       friends.where("email like ?", "%#{email}%")
    end   
    

    这将返回一个 ActiveRecord::Relation,您可以将其他条件、顺序、分页等链接到它

    user.followers_by_email("me@example.com").order(:first_name).limit(10)
    

    【讨论】:

    • 这完全有效,显然应该。我试过了,一定有一些我没有注意到的类型或东西,因为当我再次尝试时它工作得完美无缺。
    【解决方案2】:

    现在是使用活动记录范围的好时机。 http://guides.rubyonrails.org/active_record_querying.html#scopes

    这是一个简单的例子

    用户.rb

    scope :followers, friends.where(:published => true).order("created_at DESC").limit(150)
    

    在你的控制器中

    @followers = User.followers
    

    【讨论】:

      【解决方案3】:

      我似乎在以下方面取得了一些成功:

      conditions = ['contacts.user_id = ? AND users.email LIKE ? ', self.id, "%#{query}%"]
      User.includes(:inverse_friends).where(conditions)
      

      虽然它起作用很奇怪,但我不完全确定它为什么起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多