Adding tags to posts in Ruby on Rails

2019-02-08 22:11发布

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?

3条回答
干净又极端
2楼-- · 2019-02-08 22:49

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.

查看更多
仙女界的扛把子
3楼-- · 2019-02-08 22:56

Err, the usual way? Add Tag entity, add has_many :tags in your Post entity. Then migrate. That would be all.

查看更多
迷人小祖宗
4楼-- · 2019-02-08 23:05

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.

查看更多
登录 后发表回答