Ruby on Rails 3 - Rails 新手 - 了解评级应用程序的关系
我决定使用 Rails 3 构建我的最新站点。这是我第一次使用 Rails,并且希望获得社区关于如何执行以下场景的意见。
我创建了以下模型:项目、评级、用户
我希望应用程序的工作方式为:
1) 项目有很多评级
2) 用户可以提交多个评分
- 每个项目只有一个用户提交评分
3)特定评级只能有一个项目和一个用户
基于此我希望能够:
1)显示项目的所有评级
2) 显示特定用户评分的所有项目
看起来很简单。非常感谢任何帮助或指导。
I've decided to build my newest site using Rails 3. This is my first experience with Rails and wanted to get the communities opinion on how to do the following scenario.
I have the following models created: Item, Rating, User
I would like the app to work as:
1) Item has many Ratings
2) User can submit many Ratings
- Only one user submitted rating per item
3) Specific rating can can only have one Item and one User
Based on this I want to be able to:
1) Show all ratings for an item
2) Show all items rated by a particular user
Seems simple enough. Any help or direction is appreciated greatly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将使用多态关联:
这样您的用户可以对不同的项目进行评分,但每个项目只能评分一次。
要实现此目的,您需要在
ratings
表中添加rateable_id
和rateable_type
字段。另外,当然还有user_id
和rating_score
之类的。最大的优点是您可以根据需要添加任意数量的
rateables
。例如,如果您想对Song
模型进行评分,那么您可以简单地实现它,如下所示:要显示
Item
的评分:item. ratings< /代码>
要显示
用户
评分的所有项目:user.lated_items
PS我的英语语法不好,所以如果拼写错误
rateable
请纠正我< br>PPS 这个实现未经测试,是我直接从脑子里写出来的,所以不能保证它能 100% 工作:)
祝你好运!
I would use Polymorphic association:
With this your User can rate different Items, but only once per Item.
To implement this you'd need
rateable_id
andrateable_type
fields in yourratings
table. Plus, off course,user_id
andrating_score
or something.The great advantage is that you are able to add as much
rateables
as you wish. If, for example, you want to rate aSong
model, then you can simply implement it like this:To show ratings for an
Item
:item.ratings
To show all items rated by a
User
:user.rated_items
P.S. I am not good in English grammar, so correct me if have misspelled
rateable
P.P.S. this implementation is untested, I wrote it straight out of my head, so there's no guarantee it will work 100% :)
Good luck!