rails serialize and join table

    xiaoxiao2021-03-25  147

    serialize

    使用命令:

    $rails g migration add_tags_to_posts

    然后在新生成的xxx_add_tags_posts.rb 中添加:

    def change change_table :post do |t| t.text :tags end end

    然后在model/posts.rb 中添加:

    serialize :tags

    然后迁移数据库:

    rake db:migrate

    在前端代码总添加:

    <% @posts.each do |post|%> <% post.tags.each do |tag|%> <%= tag %> <% end %>

    join table

    但是这种方法有很大局限性,没办法全局获取当前已经有的tag,万一想要什么tag列表什么的就很麻烦了。所以,使用下面这种方法: has and belongs to many

    生成categories模型

    $rails g model categories name:string

    在categories的db文件中添加这句话

    create_join_table :categories, :post

    然后在post.rb中添加这句

    has_and_belongs_to_many :categories

    然后迁移数据库

    $rake db:migrate

    然后在命令行中手动添加tag,因为此时还没有图形界面

    $rails c >@post = Post.first >@post.categories.create(name: 'one')

    然后在前端代码中添加:

    这个是tag导航,能直接到有这个tag的文章,

    <% Category.all.each do |category|%> <%= link_to category.name, root_path(category: category.id), class: "blog-nav-item"%> <% end %>

    上边那段更改成这个样子

    <% @posts.each do |post| %> <%= post.publish %> by <%= post.author%> tag: <% post.categories.each do |category|%> <%= category.name %>+ <% end %> <p><%= post.content%></p>

    此时还不行,还需要controller的支持: 在posts_controller.rb文件中添加:

    注意参数的复数,在还没有完全搞清楚参数意义之前,还是先把单数复数什么的记住吧。。。

    def index @posts = if params[:category] Post.joins(:categories).where(categories: {id: params[:category]}) else Post.all end end
    转载请注明原文地址: https://ju.6miu.com/read-6110.html

    最新回复(0)