rails serialize and join table

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值