Ruby on Rails:用户喜欢歌曲时的关联
我正在尝试找出为以下场景设置数据库和模型的最佳方法。
用户可以喜欢无限数量的歌曲。 一首歌可以被无限多个用户喜欢一次。
我有这些表: 歌曲、用户、喜欢等...遵循 RoR 约定。
名为 likes 的表具有以下外键:user_id、song_id。还有一个名为“时间”的字段,用于保存喜欢歌曲的时间戳。
我不知道如何做到这一点,我希望能够在我的控制器中使用这样的代码:
User.find(1).likes.all 这不应该从喜欢表返回,而是加入歌曲表并输出用户喜欢的所有歌曲。
遵循惯例,在 Ruby on Rails 中实现这一目标的最佳实践是什么?
I'm trying to figure out the best way to setup my database and models for the following scenario.
A user can like an infinite number of songs.
A song can be liked once by an infinite number of users.
I have these tables:
songs, users, likes etc... Following RoR conventions.
The table named likes has these foreign keys: user_id, song_id. And also a field named 'time' to save a timestamp when the song was liked.
I'm not sure of how to do this, I would like to be able to use code like this in my controllers:
User.find(1).likes.all
This should not return from the likes table, but join the songs table and output all the songs that the user likes.
What are the best practises to achieve this in Ruby on Rails following their conventions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非您需要专门对
likes
表数据进行操作,否则模型本身可能不是必需的。关系很简单:这将通过当前不存在的 Song_users 表进行连接。但是,由于您希望它通过喜欢加入,您可以将每个更改为:
如果您希望能够调用 User.find(1).likes 并获取歌曲,则将用户的版本更改为:
您可以更改歌曲版本如下:
这将为您提供 Song.find(1).liked_by.all 并为您提供用户(如果您想使用第一个版本,您可以将其保留给用户)
有关 habtm 关系的更多详细信息可以在此处找到:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many
编辑添加
如果您出于某种原因想要对连接表进行操作(您发现自己需要专门针对连接的方法),您可以通过以下方式包含模型:
这将让您执行
User.find (1).songs.all
,但User.find(1).likes.all
将为您提供加入数据Unless you need to act specifically on the
likes
table data, the model itself is probably not necessary. The relationship is easy:This will join through the currently non-existent song_users table. But since you want it to join through likes you can change each one to this:
If you want to be able to call User.find(1).likes and get songs, then change the user's version to this:
And you could change the songs version to something like this:
This will give you Song.find(1).liked_by.all and give you the users (You could keep it to users if you wanted using the first version)
More details on habtm relationships can be found here: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many
Edit to add
If you want to act on the join table for whatever reason (you find yourself needing methods specifically on the join), you can include the model by doing it this way:
This will let you do
User.find(1).songs.all
, butUser.find(1).likes.all
will give you the join data