刘华佼的全栈学习记录

如何使用下拉菜单看到自己发表的所有文章

| Comments

目标

使用下拉菜单看到自己发表的所有文章

步骤一: 产生account名下的posts_controller

rails g controller account/posts
也可以写作:
rails g controller account::posts

步骤二:修改routing

config/routes.rb 加入resources :posts
namespace :account do
resource :xxxs
resource :posts
end

步骤三:下拉菜单中加入My xxxs选项

app/views/common/navbar.html.erb中dropdown-menu下面加入`

  • <%= link
  • to("My Posts", account_posts_path) %> `,如:

    <li> <%= link_to("My xxxs", account_xxxs_path) %></li>
       <li> <%= link_to("My Posts", account_posts_path) %></li> 
    <li class="divider"> </li>
    

    步骤四:新建account/posts_controller.rb下的index action

    加入:

      before_action :authenticate_user!
    
      def index
        @posts = current_user.posts
      end
    

    步骤五:新建“ 发表文章一览表”

    touch app/views/account/posts/index.html.erb

    <div class="col-md-12">
    
      <h2 class="text-center"> 我发表过的文章 </h2>
    
      <table class="table">
        <thead>
          <tr>
            <th> Content </th>
            <th> Group Name </th>
            <th> Last Update </th>
            <th colspan="2"></th>
          </tr>
        </thead>
    
        <tbody>
          <% @posts.each do |post| %>
            <tr>
              <td> <%= post.content %> </td>
              <td> <%= post.group.title %> </td>
              <td> <%= post.updated_at %> </td>
              <td> <%= link_to('Edit', edit_group_post_path(post.group, post), class: "btn btn-default btn-xs") %></td>
              <td> <%= link_to('Delete', group_post_path(post.group, post), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-default btn-xs") %></td>
            </tr>
          <% end %>
        </tbody>
      </table>
    </div>
    

    Comments

    comments powered by Disqus