Notes posted to Ruby on Rails
RSS feedAre 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..
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.
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)
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.
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 only for strings, but arrays and hashes too
exclude? is defined as !include?, meaning it is the exact opposite of include? . See the source.
This means that it works for Arrays and Hashes too, as well as for Strings.
It works for Arrays:
>> [nil].exclude?(nil) => false >> [nil].include?(nil) => true >> ["lala"].include?(nil) => false >> ["lala"].exclude?(nil) => true
And for Hashes:
>> params = {} => {} >> params[:db] = "lol" => "lol" >> params.exclude?(:db) => false >> params.include?(:db) => true >>
Redirect to subdomain
If you’re looking to redirect to a subdomain you can do things like this:
redirect_to users_url(1, params: {a: :b}, subdomain: 'bob')
Why is this deprecated?
Anyone knows?
prepend_before_filter
If you need the method to be called at *the beginning* of the before_filter chain then you should use:
Poor man's maybe
After creating a simple Maybe monad in Ruby, a colleaque noticed I could have just used try (I wasn’t aware try supports blocks). I think the method was even meant for such cases.
Why I mention this? Because it clarifies the whole ‘raises exception if method does not exist’ thing. It should not be crappy solution to exception handling, but allow for doing away with messy if statements. An example:
report = params[:query_type] .try { |qt| build_query(qt) } .try { |sql| run_query(sql) } .try { |res| format_result(res) }
If any of the expressions params[], build_query, run_query etc. returns nil, the chain is halted and nil is returned. It still throws exceptions if a values is not nil and method does not exist, which is just like it should.
Be careful with cycles
This simplistic implementation (unlike Marshal.load(Marshal.dump(object)) doesn’t handle cycles in objects.
a = {} b = {a: a} a[:b] = b a.deep_dup # SystemStackError: stack level too deep
An article about token-based authentication
www.codeschool.com/blog/2014/02/03/token-based-authentication-rails/
Have submit_tag send value as a nested resource
To have the submit_tag send it’s value within a nested resource for strong params use the name paramter.
submit_tag("Send", name: 'article[submit]')
Text improvement
Where it says: without loading a bunch of records should say: without loading a bunch of columns/attributes Considering that record usually is a row.
SQL Injection?
Note that the version of leente and timdorr are probably vulnerable to SQL Injection (through attribute param).
Probably you want to look into with_lock instead of handcrafting SQL.
arguments do not need to be an array
it’s a small point, but if you look at the source, the method is defined with the splat operator in the arguments:
def select (*fields)
this means that a list of arguments is automatically converted to an array. There is no typo in the description above.
It will also work to pass an array:
select([:field1, :field2])
although the select method interprets this as a single argument, and places it into an array (due to the splat operator), this is then passed to the _select(*fields) method, which immediately calls fields.flatten!
So either a list or an array may be passed, both will work.
How safe is this?
Could this be used against a user supplied fragment like in a url route ?
Rails 3.2 / 4.x with_scope replacement
If you’re looking for with_scope replacement for newer versions, see http://apidock.com/rails/ActiveRecord/Relation/scoping
Group method chain
The group_method parameter can be a string representing a method chain:
grouped_collection_select(:city, :country_id, @continents, 'countries.sort.reverse', :name, :id, :name)
If we were to modify the Country model so we can sort by name:
class Country include Comparable def <=>(other) self.name <=> other.name end end
The above example would have given us the countries sorted by name in descending sequence.