开发者

Model for subscriptions in rails

So I have a slightly funny model: I want to record the list of users that are subscribed to a particular thread.

At the moment I have :thread has_many :subscribers

where

subscribers takes user_id and thread_id as parameters. If the combination of user_id and thread_id is found, a user is subscribed, otherwise they are not.

If I want to subscribe a user, I need to insert this combination into the database.

If I want to 'unsubscribe' a user, I need to delete this combination from the database.

Do I need to use a standard ActiveRecord setup for this, or should I be changing it a bit more drastically? If I were doing this without a framework, I would have a joint key of task_id and user_id, but开发者_如何学Python I have no idea if this is possible in rails.

Thoughts on how to proceed?


You can use the "has_many :through" ActiveRecord association. You can find more information on the Rails Guides for Active Record.

Basically you do something like the following in your Thread model:

has_many :subscriptions
has_many :subcribers, :through => :subscriptions

And then do:

has_many :subscriptions
has_many :subscribed_threads, :through => :subscriptions

in your subscribers/user model.

In your subscriptions model, you'd have the following:

has_many :threads
has_many :subscribers

You'd need to create the thread_subscribers table and model, to wire everything up correctly. But in the end you can then do a myThread.thread_subscribers and get the list of subscribers to a thread or user.subscribed_threads to get the user's subscriptions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜