如何扩展这个 Ruby ActiveRecord 模型?
我正在创建这个小节目调度程序。
我有表格显示,带有 title:string
和 description:text
。我想向节目添加日期和时间(每个节目可以有多天,并且每天都有自己的时间)。我该怎么做呢?
我正在考虑制作一个乘法表。使用列(show_id
、day
和 time
)。然后,在列出节目时,您可以搜索符合该 show_id
的时间并按天排序。
欢迎任何想法、建议等。
I'm creating this little show scheduler thing.
I have the table shows, with title:string
and description:text
. I want to add days and times to the show (each show can have multiple days, and each day has their OWN times). How might I go about doing this?
I was thinking of making a times table. With the columns (show_id
, day
, and time
). Then when listing the show, you search for times that meet that show_id
and sort by day.
Any ideas, suggestions, etc. welcomed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将使用以下命令创建
Show
模型:然后您将创建 ShowTime 模型:
然后,在您的
show.rb
模型文件中,您将定义一个has_many
关系如下:在您的
ShowTime
模型文件中,您可以定义一个belongs_to
关系,如下所示:You'd create the
Show
model with the following command:Then you'd create the ShowTime model:
Then, in your
show.rb
model file, you'd define ahas_many
relationship like this:And in your
ShowTime
model file, you'd define abelongs_to
relationship like this:在我看来,最简单的解决方案是使用单个 DateTime 对象,因为您可以从 Time 对象获取日期和时间。
<代码>
脚本/生成模型 ShowTime 时间:datetime
脚本/生成模型 显示标题:字符串 描述:文本 显示时间:引用
然后放入 Jacob 提到的 Belongs_to/ has Many_associations 中。我认为在放映时有一个单独的模型会更好,并且具有更大的灵活性。您还应该研究 Time 对象上的 strftime 方法,以根据您的喜好设置时间格式。
Seems to me the simplest solution to this would be to use a single DateTime Object, since you can get the day and the time from a Time object.
script/generate model ShowTime time:datetime
script/generate model Show title:string description:text showtime:references
Then put in the belongs_to/ has many_associations that Jacob referred to. I think having a separate model for the showtime would be better and allow for more flexibility. You should also look into the strftime method on a Time object, to format the time to your liking.
我认为你的想法非常合理(特别是对于没有编程经验的人)。如果您对实现此目的的“Rails 方式”感兴趣,我建议检查 Rails 指南。 (总的来说,我确实推荐这个指南,因为它对我使用 Rails 帮助很大)
I think your idea is very reasonable (especially for someone who has no experience with programming). If you're interested in "Rails way" of implementing this, I would recommend checking
has_many
relationship in the Rails guide. (And I do recommend this guide in general, as it helped me a lot with Rails)