我正在编写一个论坛系统(在Ruby中,使用Sequel),其中一个要求是用户能够'#star;" star"一个线程,它模糊地等同于" subscription"大多数论坛都支持。我不确定如何在数据库中存储主演,特别是如何查询给定用户的已加星标/未加星标的线程,或检查线程是否已加星标。
任何提示都会非常感激,如果你碰巧知道续集的方式,一个示例模型绝对是宏伟的。
答案 0 :(得分:1)
实施起来非常简单:
create_table(:subscriptions, ignore_index_errors: true) do
primary_key :id
column :created_at, 'timestamp with time zone'
foreign_key :user_id, :users, null: false, key: [:id], index: true, on_delete: :cascade
foreign_key :thread_id, :threads, null: false, key: [:id], index: true, on_delete: :cascade
end
class Subscription < Sequel::Model
many_to_one :user
many_to_one :thread
end
class User < Sequel::Model
one_to_many :subscriptions
many_to_many :subscribed_threads,
class: :Thread,
join_table: :subscriptions,
left_key: :user_id,
right_key: :thread_id
end
class Thread < Sequel::Model
one_to_many :subscriptions
many_to_many :subscribers,
class: :User,
join_table: :subscriptions,
left_key: :thread_id,
right_key: :user_id
end
# all threads a user is subscribed to
user.subscribed_threads
# all subscribers to a thread
thread.subscribers
# all subscriptions to a thread in the last 3 days
thread.subscriptions.where{created_at >= Date.today - 3}
我建议您在所有模型上配置数据集关联插件:
# Make all model subclasses create association methods for datasets
Sequel::Model.plugin :dataset_associations
然后,您可以通过更方便地与条件关联来编写和链接查询:
# all new subscribers for a thread in the last 3 days who are moderators
thread.subscriptions.where{created_at >= Date.today - 3}.user.where(moderator: true)
有一些强大的过滤和查询功能: