Recent notes
RSS feedSpace before the opening [
In this example
Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
The array is a parameter, so a space is required before the opening [, which is equivalent to write like this
Post.find_by_sql(["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date])
Use :where or any defined scope before :find_or_create_by
You can chain find_or_create_by with :where, or any custom scope.
E.g.:
User.where(girls: true).find_or_create_by(first_name: ‘Scarlett’)
scope :celebrities, -> { where(celebrity: true) }
User.celebrities.create_with(last_name: ‘Johansson’).find_or_create_by(first_name: ‘Scarlett’)
Not a one-to-one-relationship
It’s incorrect to state that belongs_to “Specifies a one-to-one association with another class”.
If the inverse association is has_one then the model specifying belongs_to is the LHS of a zero/one-to-one relationship.
If the inverse association is has_many then the model specifying belongs_to is the LHS of a zero/many-to-one relationship.
Unless you know what the inverse association is, all you can assume is that instances of a class specifying a belongs_to association can be related to at most a single instance of the other class.
render with variables
perient view
Code example
<%= render 'time_select', locals: { select_name: 'from_tiem'}%>
render view
Code example
<%= locals[:select_name] %>
not:
Code example
<%= local_assigns[:select_name] %>
Constants
Reading source one can find detailed patterns: github.com/ruby/ruby/blob/ruby_1_9_3/lib/uri/common.rb
Not exactly like map {}.flatten
To also give dimension, is about 4.5 times faster then map {}.flatten.
Are those supported versions correct?
It seems like this method was supported in versions prior to 4.0.2.
UPDATE never mind, wish I could delete this comment..
RE: Convert an Array of Arrays to a Hash using inject
Another way to convert an array of arrays to a hash using inject:
array = [['A', 'a'], ['B', 'b'], ['C', 'c']] hash = array.inject({}) do |memo, values| memo.merge!(values.first => values.last) end hash # => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
This doesn't write files
This doesn’t write files, at least not anymore. Since at least rails 4 `Rack::Cache` isn’t included by default. In any case this method only ever set headers on the response.
Very bad documentation
This is terrible documentation. It makes it very hard to understand what the arguments mean.
The signature is
alias_method(p1, p2)
So what do p1 and p2 mean? The description doesn’t refer to them at all, but to new_name and old_name. How are we supposed to know which is which?
And then it gets even worse in the code sample:
alias_method :orig_exit, :exit
From the naming it sounds like the first argument is the original method name.
Documentation is supposed to resolve this kind of confusion, not create it.
Prevent new line character.
To prevent the “\n” character added at the end of each file pass in the “row_sep: nil” option:
[ "some", "array" ].to_csv # => "some, array\n" [ "some", "array" ].to_csv( row_sep: nil ) # => "some, array"
Link with relative url
By default link_to opens url as absolute if path does not contain http:// or https:// For Ex.
link_to ‘View’, “test123.abc.com/ag/acf”, target: :_blank, title: “Click to open url in a new tab”
Then it’ll open the link with absolute path not only with test123.abc.com/ag/acf.
If link_to path contains http:// then it takes the relative url.
link_to ‘View’, “http://test123.abc.com/ag/acf”, target: :_blank, title: “Click to open url in a new tab”
Now it open the relative url as it contains.
add index directly
You can add an index now directly on the foreign_key :
t.references(:user, index: true)
RSS feeds in Rails
Fetching RSS feeds in the request/response cycle inside a Rails application is probably not the very best approach, as it will make your application as slow as the server serving RSS feeds. Another option is to do it asynchronously using a worker or a queue, but this can also become quite complex and hard to maintain over time.
Another solution is to use an API like superfeedr.com and its Rails Engine (http://blog.superfeedr.com/consuming-rss-feeds-rails/). All the polling and parsing is done on Superfeedr’s side and your application is notified in realtime as soon as the resources are updated using a webhook pattern.
Deprecation
It still exists but you give it a block instead of creating a method:
<=2.3.8
def before_create self.login = self.first_name end
Now
before_create :set_login def set_login self.login = self.first_name end
What object_name.method values will result in checked chekboxes.
*It’s intended that method returns an integer and if that integer is above zero, then the checkbox is checked.* - more exactly, that’s how it’s determined whether value will be checked or not:
(`@checked_value` is checked_value, `value` is what object_name.method returns)
def checked?(value) case value when TrueClass, FalseClass value == !!@checked_value when NilClass false when String value == @checked_value else if value.respond_to?(:include?) value.include?(@checked_value) else value.to_i == @checked_value.to_i end end end
Parent associations are kept
Maybe this information will save you some time: parent associations (i.e. associations with foreign id in current record) are copied. Don’t assume you’ll get a safely editable object.
Passing a block does not behave as expected
When the condition is true, the block is not rendered:
<%= link_to_if true, users_path, {}, {} do %> <i class='fa fa-star'></i> <% end %>
renders:
<a href="/users">/users</a>
But if the condition is false, the block will render:
<%= link_to_if false, users_path, {}, {} do %> <i class='fa fa-star'></i> <% end %>
renders:
<i class='fa fa-star'></i>
If condition is false, options hash is ignored
Here, the class will be ignored:
<%= link_to_if false, 'Home', root_path, class: 'link' %> #=> Home
Save yourself a little typing
We often have a form with a select box that selects a model association. So for example to select a colour, when there is an associated Colour model, a select box will typically select :colour_id.
In this case, ActionView automatically humanizes :colour_id to produce “Colour” as the label text.
enumerator and number of lines to read
Example
File.foreach(filename) .take(number_of_lines) .map do |line| # ... stuff ... end
Wrong number of arguments (2 for 1)
If you get this error, wrap brackets with parentheses: Post.find_by_sql([“some query”])
number_field tag does not accept the same options as text_field_tag
number_field_tag does not accept the size or maxlength options; the max option for number_field_tag is used to control the size of the field. According to W3 http://www.w3.org/TR/html-markup/input.number.html , placeholder should be accepted, but I don’t find that this works in the way it works for text_field_tag.
Transactions and Stale ORM Data
Consider the following:
foo = Foo.new bar = Bar.new ActiveRecord::Base.transaction do foo.save! # succeeds bar.save! # failure, validation problem end foo.persisted? # true (!)
foo was not permanently stored in the database, but it was transiently saved, and this is reflected in the ActiveRecord model still in memory. But if you try
foo.reload # raises ActiveRecord::RecordNotFound
Don’t let stale data confuse you after using transactions!
Edited to add: This particular example does not succeed in reproducing the issue I encountered, which involved a slightly more complicated set of nested transactions. I haven’t managed to produce a simple test case where stale data remains in the model, but I have definitely experienced it in my app.
Transactions and Stale ORM Data
Consider the following:
ActiveRecord::Base.transaction do foo = Foo.new foo.save # succeeds bar = Bar.new bar.save # failure, validation problem end
defaults to 40 columns, 20 rows
as you can see in InstanceTag
Not exactly like map {}.flatten
To clarify on the last comment, conceptually it’s the same, but #flat_map will perform better because there is no need to create an intermediate Array
clarification of inputs
“split(p1 = v1, p2 = v2)”
in reading the rest of the documentation, i found “p1” and “p2” to be confusing.
I think it should be:
split( pattern, limit )