Skip to content

Instantly share code, notes, and snippets.

@tmattia tmattia/gist:1374045
Created Nov 17, 2011

Embed
What would you like to do?
[RoR] Validate length of relationship
$ rails console
Loading development environment (Rails 3.1.1)
ruby-1.9.2-p290 :001 > c = Client.create
SQL (16.3ms) INSERT INTO "clients" ("name") VALUES (?) [["name", nil]]
=> #<Client id: 11, name: nil>
ruby-1.9.2-p290 :002 > 3.times do c.orders.create end
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = 11 LIMIT 1
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."client_id" = 11
SQL (0.4ms) INSERT INTO "orders" ("client_id") VALUES (?) [["client_id", 11]]
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = 11 LIMIT 1
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."client_id" = 11
SQL (0.3ms) INSERT INTO "orders" ("client_id") VALUES (?) [["client_id", 11]]
Client Load (0.1ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = 11 LIMIT 1
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."client_id" = 11
SQL (0.2ms) INSERT INTO "orders" ("client_id") VALUES (?) [["client_id", 11]]
=> 3
ruby-1.9.2-p290 :003 > c.valid?
=> true
ruby-1.9.2-p290 :004 > c2 = Client.create
SQL (0.6ms) INSERT INTO "clients" ("name") VALUES (?) [["name", nil]]
=> #<Client id: 12, name: nil>
ruby-1.9.2-p290 :005 > 4.times do c2.orders.create end
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = 12 LIMIT 1
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."client_id" = 12
SQL (0.3ms) INSERT INTO "orders" ("client_id") VALUES (?) [["client_id", 12]]
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = 12 LIMIT 1
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."client_id" = 12
SQL (0.2ms) INSERT INTO "orders" ("client_id") VALUES (?) [["client_id", 12]]
Client Load (0.1ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = 12 LIMIT 1
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."client_id" = 12
SQL (0.4ms) INSERT INTO "orders" ("client_id") VALUES (?) [["client_id", 12]]
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = 12 LIMIT 1
Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."client_id" = 12
SQL (0.3ms) INSERT INTO "orders" ("client_id") VALUES (?) [["client_id", 12]]
=> 4
ruby-1.9.2-p290 :006 > c2.valid?
=> false
ruby-1.9.2-p290 :007 > c2.orders.length
=> 4
ruby-1.9.2-p290 :008 > c2.orders.count
(0.3ms) SELECT COUNT(*) FROM "orders" WHERE "orders"."client_id" = 12
=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.