4. âandâ or â&&â
What does this mean?
result = func(arg) and render(:text => result)
Why not this?
result = func(arg) && render(:text => result)
5. âandâ or â&&â
What does this mean?
result = func(arg) and render(:text => result)
Why not this?
result = func(arg) && render(:text => result)
Be aware of the operator precedence
6. strip_tags
Display user input text without tags
What we did:
7. strip_tags
When
text =
â<img title="http://example.com/x.js?" src="#"â
the page becomes:
<p> <img title="http://example.com/x.js?" src="#" </p>
9. cache
class Blog1Controller < ApplicationController
def list
unless read_fragment(:action => 'list')
@articles = Article.ďŹnd_recent Controller
end
end
end
<% cache do %>
<ul>
<% for article in @articles -%>
<li><p><%= h(article.body) %></p></li> list.html.erb
<% end -%>
</ul>
<% end %>
10. cache
Result:
sometime got crash due to
uninitialized @articles
18. cache
article list article new
check cache list expire cache
render
check cache
19. cache
article list article new
check cache list expire cache
render
check cache
crashed by non-init
@articles
20. cache
Solutions?
⢠defensive: handle the exception
⢠postpone init of @articles
⢠update caches instead of expiring them
none of them is perfect
25. validate_uniqueness_of
We always get errors like this:
A ActiveRecord::StatementInvalid occurred in
fund#add_watch_fund:
 Mysql::Error: Duplicate entry '1234-271' for key 2:
INSERT INTO `watch_funds` (`account_id`,
`position`, `fund_id`, `created_at`) VALUES(1234, 19,
271, '2009-05-06 19:13:50')
34. conditions
Background:
⢠category has many subcategories
⢠subcategory has many posts
⢠post belongs to subcategory
we need to select all posts in a category.
35. conditions
What we did:
named_scope :in_category, lambda { |cat|
conditions = [cat.subcategories.map {|subcat|
'posts.subcategory_id = ?'
}.join(" OR ")]
cat.subcategories.each {|subcat|
conditions << subcat.id }
{:conditions => conditions}
}
37. conditions
When category has no subcategory
named_scope :in_category, lambda { |cat|
conditions = [cat.subcategories.map {|subcat|
'posts.subcategory_id = ?'
}.join(" OR ")]
cat.subcategories.each {|subcat|
conditions << subcat.id }
{:conditions => conditions}
}
38. conditions
When you compose conditions, be
aware that sometime nothing to
compose means
the conditions should match nothing,
not the conditions should be empty.
39. before_create
set a ďŹag if the author of the post is an admin
What we did:
action controller &#x76F8;&#x5173;&#x7684;&#x95EE;&#x9898;\nAnything you place in the flash will be exposed to the very next action and then cleared out.\n
Anything you place in the flash will be exposed to the very next action and then cleared out.\n