【问题标题】:complex ActiveRecord query - search within hash复杂的 ActiveRecord 查询 - 在哈希中搜索
【发布时间】:2012-11-15 19:04:17
【问题描述】:

三个表,用于分布式图书馆系统:

Class Book       # model: id, name, auhtor
  has_many :book_belongs
  has_many :owners, through: :book_belongs, source: :user

Class User       # model: id, name, email, facebook_uid, facebook_friends
  has_many :book_belongs
  has_many :ownedbooks, through: :book_belongs, source: :book

Class BookBelong # model: user_id, book_id
  belongs_to :user
  belongs_to :book

@user.facebookfriends 是一个(序列化)散列,包含用户 facebook 朋友的 facebook_id 和 facebook_name

我在设计 ruby​​/rails activerecord 查询时遇到问题:

  • 返回 Facebook 好友拥有的图书。

在“英语”中,查询应该查看图书所有者 facebook_id 并匹配用户 facebook_friends 哈希。

  • 是否有更好的方法来设计表/数据模型以使其更简单且计算成本更低?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    好的 - 解决了,正在使用

    BookBelong.joins(:book).joins(:user).where('users.uid' => current_user.friends.keys) 
    

    并使用简单的方法在视图中获取实际书籍

      <% @friends_books.each do |book| %>
        <td><%= book.book.name %></td>
    

    不过,似乎并不是超级高效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 2022-11-12
      • 2012-05-21
      相关资源
      最近更新 更多