在 Ruby on Rails 中向帖子添加标签
我正在使用脚手架在 Rails 中创建一个博客。我想在每个帖子上添加一个“标签”字段,就像 StackOverflow 和 WordPress 上的那样。我可以使用字符串类型( railsgeneratescaffoldposttitle:stringbody:texttags:string
)然后用逗号分隔来完成此操作,但这不是一个好的做法,因为我希望读者按标签浏览(例如 /tags/web20
或 /tags/lol
)。我该怎么做?
I am creating a blog in Rails using Scaffolding. I want to add a 'tags' field on each post like on StackOverflow and WordPress. I can do this with the string type ( rails generate scaffold post title:string body:text tags:string
) and then comma separated, but it's not good practice since I want the reader to browse by tags ( e.g. /tags/web20
or /tags/lol
). How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
标记如此普遍,以至于实现成为一种商品。我相信 "acts as taggable on" 通常是实现标签的首选方式。
请在此处查看其他流行的解决方案。
如果您想自己实现它,您可以深入研究源代码来寻找一些想法。
Tagging is so common that implementations are a commodity. I believe "acts as taggable on" is usually the preferred way of implementing tags.
See other popular solutions here.
If you wish to implement it yourself, you could dive into the source code to find some ideas.
我建议创建一个标签模型并使用
has_and_belongs_to_many
为帖子分配标签。我不知道脚手架功能是否会帮助您为此创建一个表单,但自己添加它应该不难。我还建议使用 formattastic 插件,因为用它创建表单更容易、更好。I would suggest creating a Tag model and using
has_and_belongs_to_many
to assign tags to posts. I don't know if the scaffold feature will help you create a form for that, but it shouldn't be difficult to add it yourself. I also suggest using the formtastic plugin as it's much easier and nicer to create forms with it.呃,通常的方式吗?添加 Tag 实体,在您的 Post 实体中添加
has_many :tags
。然后迁移。仅此而已。Err, the usual way? Add Tag entity, add
has_many :tags
in your Post entity. Then migrate. That would be all.