Rails 构建评论功能(2)

2021-10-20 10:01:55 浏览数 (2)

添加删除模型

rails 命令可以方便的添加删除模型

代码语言:javascript复制
[root@h202 blog]# rails --help 
Usage: rails COMMAND [ARGS]

The most common rails commands are:
 generate    Generate new code (short-cut alias: "g")
 console     Start the Rails console (short-cut alias: "c")
 server      Start the Rails server (short-cut alias: "s")
 dbconsole   Start a console for the database specified in config/database.yml
             (short-cut alias: "db")
 new         Create a new Rails application. "rails new my_app" creates a
             new application called MyApp in "./my_app"

In addition to those, there are:
 destroy      Undo code generated with "generate" (short-cut alias: "d")
 plugin new   Generates skeleton for developing a Rails plugin
 runner       Run a piece of code in the application environment (short-cut alias: "r")

All commands can be run with -h (or --help) for more information.
[root@h202 blog]# rails generate model Comment commenter:string body:text
Running via Spring preloader in process 3716
      invoke  active_record
      create    db/migrate/20160427081218_create_comments.rb
      create    app/models/comment.rb
      invoke    test_unit
      create      test/models/comment_test.rb
      create      test/fixtures/comments.yml
[root@h202 blog]# 
[root@h202 blog]# rails destroy model Comment 
Running via Spring preloader in process 3763
      invoke  active_record
      remove    db/migrate/20160427081218_create_comments.rb
      remove    app/models/comment.rb
      invoke    test_unit
      remove      test/models/comment_test.rb
      remove      test/fixtures/comments.yml
[root@h202 blog]#

添加一个评论模型

代码语言:javascript复制
[root@h202 blog]# rails generate model Comment commenter:string body:text article:references
Running via Spring preloader in process 3787
      invoke  active_record
      create    db/migrate/20160427082552_create_comments.rb
      create    app/models/comment.rb
      invoke    test_unit
      create      test/models/comment_test.rb
      create      test/fixtures/comments.yml
[root@h202 blog]# cat db/migrate/20160427082552_create_comments.rb
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :commenter
      t.text :body
      t.references :article, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end
[root@h202 blog]# cat app/models/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :article
end
[root@h202 blog]# cat test/models/comment_test.rb
require 'test_helper'

class CommentTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end
[root@h202 blog]# cat test/fixtures/comments.yml
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

one:
  commenter: MyString
  body: MyText
  article_id: 

two:
  commenter: MyString
  body: MyText
  article_id: 
[root@h202 blog]#

0 人点赞