RoR operation summary

Published on:

今天看到@yanni 写的总结,觉得不错,我就抄过来,顺便根据自己的情况做一个关于实操命令的总结。

1. 新建和删除repo或文件

rails new rails101
rm -rf rails101(特别是如果在根目录下误操作了rails new,可以这样用命令删除)
mkdir app/views/common
touch app/views/common/navbar.html.erb
rm app/views/posts/show.html.erb

2. 新建一个scaffold(封装了MVC)

  • rails g scaffold topic title:string description:text
  • rake db:migrate

3. 新建一个model

  • rails g model group title:string description:text
  • rake db:migrate

4. 新增一个controller

  • rails g controller welcome
  • touch app/views/welcome/index.html.erb

  • rails g controller account/groups(在controllers和views都新增一个account文件夹,文件夹下有groups)

  • routes.rb 修改

   namespace :account do
    resources :groups
  end

5. 新增 user_id 到 group 的 table 里

  • rails g migration add_user_id_to_group
  • 修改文件:db/migrate/一串数字add_user_id_to_group
    class AddUserIdToGroup < ActiveRecord::Migration[5.0]
    def change
    addcolumn :groups, :user_id, :integer
    end
    end
    
  • rake db:migrate

6. rails console

Group.create(title: "Board 1", description: "Board 1 body")
Group.delete_all

u = User.first
g = Group.first
g.members << u
g.members
u.participated_groups

7. about model

validates :title, presence:true(比如修改groups.rb)
scope :recent, -> { order("created_at DESC")}
@posts = @group.posts.recent.paginate(:page => params[:page], :per_page => 5)

8.about devise

rails generate simple_form:install --bootstrap (simple_form only)
rails g devise:install (devise only)
rails g devise user (devise only)
rake db:migrate
restart rails server (rails s)
*_controller.rb 文件修改

9.limit user or preaction

before_action :authenticate_user! , only: [:new, :create, :edit, :update, :destroy

before_action :find_group_and_check_permission, only: [:edit, :update, :destroy]
javascript

10. 统筹

用app/views/layouts/application.html.erb来统筹navbar和footer。

<!DOCTYPE html>
<html>
    <head>
        <title>Rails101</title>
        <%= csrf_meta_tags %>

        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
        <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    </head>

    <body>

        <div class="container-fluid">
            <%= render "common/navbar" %>
            <%= yield %>
        </div>

        <%= render "common/footer" %>

    </body>
</html>

Comments

comments powered by Disqus