如何在RubyonRails应用程序中为每个用户的状态建模



我正在开发RubyonRails播客捕获器,我不知道如何对每个用户的事件状态进行建模。

我想要一个模型,包括关于一集的信息,以及用户是否播放了这集或他们对它的评分。

表格如下:

episodes_1
id | user_id | podcast_id | title | audio_url | duration| is_played | rating

如果许多用户订阅了相同的播客,那么会有许多相同的记录title和audio_url,所以我想到了另一个表表示:

episodes_2
id | podcast_id | title | audio_url | duration
user_episode_data
id | user_id | episode_id | is_played | rating

如果您在user_episode_data.episode_id = episode_2.id上加入user_episode_dataepisodes_2,您将得到一个包含episodes_1中所有信息的表

第二种选择似乎是存储数据的更好方式,但第一种选择似乎更适合显示数据。

是否可以使用多个表来存储一个模型?

class Podcast < AcitiveRecord::Base
has_many :episodes
end
class Episode < ActiveRecord::Base
belongs_to :podcast
has_many :user_episode_datas
end
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :podcast
end
class User < ActiveRecord::Base
has_may :subscriptions
has_may :podcasts, through: :subscriptions
has_may :episodes, through :podcasts
has_many :user_episode_datas
end
class UserEpisodeData < ActiveRecord::Base
belongs_to :user
belongs_to :episode
end

我希望user.episodes返回他们订阅的每个播客的所有剧集的集合,如果该用户播放了该剧集,我希望user.episodes.first.is_played返回true,但剧集模型不属于任何用户,所以我不知道如何在rails 中建模剧集和user_epiode_data之间的一对一关系

没有必要以建议的方式设置这些关系。相反,将EpisodeUser建模为has_many :through关系:

class User < ActiveRecord::Base
has_many :views
has_many :episodes, through: :views
end
class View < ActiveRecord::Base
belongs_to :user
belongs_to :episode
end
class Episode < ActiveRecord::Base
has_many :views
has_many :users, through: :views
end

规范的Rails指南提供了一个示例的解释,该示例与您所描述的场景非常相似。以下是关于has_many :through关系的说明:

has_many:through关联通常用于建立与另一个模型的多对多连接。这种关联表明,通过继续进行第三个模型,声明模型可以与另一个模型的零个或多个实例相匹配。

请注意,在上面的示例中,View模型有效地充当了联接表。如果要将属性添加到EpisodeUser之间的关系中——例如,has_playedrating——则需要将这些属性添加到View模型中。

最新更新