Well, previouse article I had talked about What’s New in Rails4 ActiveRecord Finder?. Today please keep going to take a look “What’s New in Rails4 ActiveModel?”:
SCOPES
eager-evaluated scopes are deprecated
- Rails3:
1 2 |
|
Warning:
- Useing #scope without passing a callable object is deprecated.
- Calling #default_scope without a block is deprecated.
- Rails4:
Scopes should take a proc object:
1
|
|
Defaults scopes should take proc object or a block:
1 2 |
|
RELATION#NONE
- Rails3:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 |
|
@posts.recent error when ‘Bad User’ because NoMethodError: undefined method ‘recent’ for []:Array.
One way we can fix this:
1 2 3 4 5 6 |
|
Rails4:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 |
|
Post.none returns ActiveRecord:Relation and never hits the database and @posts.recent no need to check for presence.
RELATION#NOT
Rails3:
1
|
|
When author is nil it’s going to generate incorrect SQL syntax: SELECT "posts".* FROM "posts" WHERE (author != NULL)
One way we can fix this:
1 2 3 4 5 |
|
Rails4:
1
|
|
When author is nill it’s goint to generate correct SQL syntax: SELECT "posts".* FROM "posts" WHERE (author IS NOT NULL)
RELATION#ORDER
case1
Rails3:
1 2 3 4 5 |
|
It’s going to generate SQL: SELECT * FROM users ORDER BY name asc, created_at desc
, new calls to order are appended.
Rails4:
1 2 3 4 5 |
|
It’s going to generate SQL: SELECT * FROM users ORDER BY created_at desc
, name asc New calls to order are prepend.
case2
Rails3:
1
|
|
Rails4:
1
|
|
It’s going to generate SQL: SELECT * FROM users ORDER BY name asc, created_at desc
Rails3:
1
|
|
Rails4:
1
|
|
It’s going to generate SQL: SELECT * FROM users ORDER BY created_at desc
So far so good, ActiveModel in Rails4 is better. :)