Subscribers model in rails
Consider a model for keeping user id's of subscribers on a particular comment thread, such tha开发者_高级运维t
thread has_many subscribers
where subscribers is of type user.
I feel like generating a new a table for subscribers is overkill. In principle, I'd like to access thread.subscribers to get a list of subscribers- surely there is a 'lighter' way?
I'm using Rails 3 with SQLite.
There are two methods you could use.
Options One is to use a habtm relationship like:
class Thread
has_and_belongs_to_many :users
end
However personally I would use an additional model, so that should you even need it you can specify stuff about subscriptions:
class Thread
has_many :subscriptions
end
class Subscription
belongs_to :thread
belongs_to :user
end
Generally a useful join model is considered better practice.
Additionally I wouldn't really be worrying about how 'light' you database schema is. Databases are very good at what they're good at, and that's why we let they do it. Encoding this kind of information as a string or the like as other issues and may even be less efficient.
Just store it is a regular attribute on the Thread
model, corresponding to a column in the threads
table. Call it subscriber_list
, and define it as a pipe-delimited list of subscribers. In the database, make it type :text
.
Then in Thread
just create a couple accessors:
class Thread < ActiveRecord::Base
def subscribers
self.subscribers_list.split('|')
end
def subscribers=(arr)
self.subscribers_list = arr.join('|')
end
end
精彩评论