rails generate model photo title:string album:references
这会产生一个album_id列,当建立belongs_to关联时,需要用到。
references算时一种结构,会产生integer.
For integer, string, text and binary fields, an integer in curly braces will be set as the limit: `rails generate model user pseudo:string{30}`
For decimal, two integers separated by a comma in curly braces will be used for precision and scale: rails generate model product ‘price:decimal{10,2}‘
You can add a `:uniq` or `:index` suffix for unique
`rails generate model user pseudo:string:uniq`
`rails generate model user pseudo:string:index`
You can combine any single curly brace option with the index options:
`rails generate model user username:string{30}:uniq`
Database Configuration
config/database.yml中可以看到默认的数据库配置。
development:
<<: *default
database: db/development.sqlite3
使用sqlite3+路径, 进入控制台。
$ sqlite3 db/development.sqlite3
SQLite version 3.14.0 2016-07-26 15:17:14
Enter ".help" for usage hints.
sqlite> .tables#显示所有表格
ar_internal_metadata products
countries schema_migrations
sqlite> .schema countries#打印创建表格的命令。
CREATE TABLE "countries" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "population" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
(0.2ms) SELECT COUNT(*) FROM "albums" WHERE "albums"."release_year" BETWEEN ? AND ? AND "albums"."id" BETWEEN ? AND ? [["release_year", 1960], ["release_year", 1966], ["id", 1], ["id", 5]]
=> 4
这里使用了in,用于精确的指定查询条件
> Album.where(release_year:[1966, 1968]).count
(0.1ms) SELECT COUNT(*) FROM "albums" WHERE "albums"."release_year" IN (?, ?) [["release_year", 1966], ["release_year", 1968]]
=> 4
这里order by 和 ASC, limit
> Album.where(release_year:[1966, 1968]).first
Album Load (0.2ms) SELECT "albums".* FROM "albums" WHERE "albums"."release_year" IN (?, ?) ORDER BY "albums"."id" ASCLIMIT ? [["release_year", 1966], ["release_year", 1968], ["LIMIT", 1]]
=> #<Album:0x00007ffd8cb9b388...>
所有查询语法,条件都可以使用?, (?, ?)代替,在语法最后使用Array,按顺序列出具体条件。
not ,or
这里使用了!=
> Album.where.not(release_year: 1968).count
(0.1ms) SELECT COUNT(*) FROM "albums" WHERE "albums"."release_year" != ? [["release_year", 1968]]
=> 9
这里使用了数据库的or,另外rails语法,or()方法连接的应该是同一个数据库
> Album.where(release_year:1967).or(Album.where(name: "The Beathles")).count
(0.2ms) SELECT COUNT(*) FROM "albums" WHERE ("albums"."release_year" = ? OR "albums"."name" = ?) [["release_year", 1967], ["name", "The Beathles"]]
=>SELECT "albums".* FROM "albums" WHERE "albums"."release_year" BETWEEN ? AND ? ORDER BY "albums"."release_year" ASC LIMIT ? [["release_year", 1965], ["release_year", 1968], ["LIMIT", 3]]
=> (42.5ms) SELECT SUM("albums"."release_year") FROM "albums" WHERE "albums"."release_year" BETWEEN ? AND ? [["release_year", 1970], ["release_year", 1979]]