Flowdock

Notes posted to Ruby on Rails

RSS feed
April 24, 2014 - (<= v4.0.2)
1 thank

First example's output is incorrect

Everything except the initially html_safe input should be escaped in the output.

The output of the first example should be:

# => "<p>foo</p>&lt;br /&gt;&lt;p&gt;bar&lt;/p&gt;"
April 23, 2014
0 thanks

Does not symbolize hashes in nested arrays

If you have a nested structure containing arrays of hashes, you still need to do that on your own, eg.

module SymbolizeHelper
  def symbolize_recursive(hash)
    {}.tap do |h|
      hash.each { |key, value| h[key.to_sym] = map_value(value) }
    end
  end

  def map_value(thing)
    case thing
    when Hash
      symbolize_recursive(thing)
    when Array
      thing.map { |v| map_value(v) }
    else
      thing
    end
  end
end

Or, if you want to get really fancy with Ruby refinements (YMMV), one could do

module SymbolizeHelper
  extend self

  def symbolize_recursive(hash)
    {}.tap do |h|
      hash.each { |key, value| h[key.to_sym] = transform(value) }
    end
  end

  private

  def transform(thing)
    case thing
    when Hash; symbolize_recursive(thing)
    when Array; thing.map { |v| transform(v) }
    else; thing
    end
  end

  refine Hash do
    def deep_symbolize_keys
      SymbolizeHelper.symbolize_recursive(self)
    end
  end
end

And later say

using SymbolizeHelper # augmented Hash#deep_symbolize_keys is now available
April 21, 2014 - (>= v4.0.2)
0 thanks
April 19, 2014
0 thanks

Compatible with old docs

Library is moved, so old library documentation is compatible http://apidock.com/rails/v3.0.9/ActionController/Streaming/send_file

April 14, 2014 - (v3.2.13)
0 thanks
April 9, 2014 - (>= v4.0.2)
0 thanks

Requires inheritance of ActionController::Metal

The example code will not work unless class inherits from ActionController::Metal (to get functioning controller) or at least AbstractController:Base.

April 1, 2014
1 thank

Sometimes, you need the "Oxford comma"

Re: Gramatical error

http://imgur.com/fycHx

We invited the strippers, JFK, and Stalin.

versus the appositive phrase:

We invited the strippers, JFK and Stalin.

(Really, you need to see the comic to appreciate the difference.)

April 1, 2014
0 thanks

Grammatical error

Hi - not sure where I would submit this so just putting here. My apologies if not in the right place.

default: “, and ” - this is grammatically wrong. There should be no comma with the last and.

Example:

[‘one’, ‘two’, ‘three’].to_sentence

should give: “one, two and three”

There is no ‘ .… , and ’ which is considered grammatically incorrect I feel. The ‘and’ does it’s job in the English language quite well by joining the two words it’s in between.

Thank you.

March 27, 2014
0 thanks

Update for Rails 4

In the example

select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })

It can be updated to

select("post", "person_id", Person.pluck(:name, :id), { include_blank: true })
March 10, 2014
0 thanks

gives a parameter

As a note, you can use it like this:

after_save {|instance|

}

it will pass in the instance being saved.

March 7, 2014
0 thanks

form_for with :path route

Similar to danwich’s note, if you specify a route using the :path option

resource :posts, path: 'articles'

then the form_for tag must specify the :url option

form_for(@post), url: post_path(@post)
February 25, 2014
1 thank

missing :through option

So the way to do the equivalent of a has_many :through is to use has_one :through, with the expected names.

so using the other example we could do

eg

class Person < ActiveRecord::Base
  belongs_to :team
  ...
end
class Task < ActiveRecord::Base
  belongs_to :person
  has_one :team, :through => :person
end
February 21, 2014
0 thanks
February 19, 2014
0 thanks

Rendering JSONP

If you provide the :callback option with a nil value, then the default JSON object will be returned. As such, this makes creating JSONP response from the render syntax very easy in your controllers, like so:

render json: @object, callback: params[:jsoncallback]
February 3, 2014
0 thanks

Symbols more performant than strings

>> options_from_collection_for_select(@posts, :slug, :title, params[:slug])

Consider using symbols for performance, otherwise it will generate a string each time instead of a symbol which will reference the same object.

January 16, 2014
0 thanks

Storing array values

I tried to add a array value using hidden_field_tag and access it in jquery. It just returns the flattened version of array. eg:(If i try to store [1,[1,2,3]] in hidden_field_tag , in jquery iam just getting ‘1 1 2 3’) but if i use input field with type=hidden iam getting the correct value. Why is that?

January 12, 2014
0 thanks

using hash as order

order can be specified as a hash, e.g.:

order(id: :desc)

This will prevent “ambiguous column” errors when the order is used with joins or includes.

January 9, 2014 - (v3.2.13)
0 thanks

onChange Event

Hello,

I’m brand new to ROR and in general server side programing. I’m a iOS developer who is trying to learn ROR.

I’m trying to use collection select to implement filtering for my page. The idea is there are a bunch of posts and I want to implement record filtering for those.

The first collection box would have parameters like “Date”, “Amount”, “Category” and based on the selection of this a secondary drop down would appear and allow the user to make a selection. The records on this page would be then filtered based on both the selection.

I have been trying out many things and have googled a lot on collection but I have reached a dead end now. I’m pretty new and just started learning ROR.

You help is much appreciated here.

Thanks in advance.

Note: the code below might be wrong and as of now its not even compiling.. currently it complaints of “remote_function” not defined…


I have a page that looks like this,

<div class=“span8”>

<% if @user.spendings.any? %>

    <h3> Spendings (<%= @user.spendings.count  %>)</h3>

    <%= collection_select(:category, :category, Category.all, :id, :name, 

{:prompt => 'Select'})%>

<%= collection_select :event, :filterType, Filters.all, :id, :filterType, {},

  {

  :onchange => remote_function(

    :url => {:action => "updatelevel", :controller => "Spendings", :id => 1},

    :with => "'level_id='+this.value"

  )}

%>

      <ol class="spendings">

        <%= render @spendings %>

      </ol>

      <%= will_paginate @spendings %>

  <% end %>

</div>
January 8, 2014 - (v3.0.0 - v3.2.13)
2 thanks

An Example for using it.

Call it in a before filter in your Base or Application Controller.

before_filter :authenticate_through_api_client

def authenticate_through_api_client

# this block should return true or false
authenticate_or_request_with_http_token |token,other_options|
 Apiclient.find_by_client_key(token).present?
end

end

# Sample request type: it expects a token in headers as

Authorization:Token token=“your_token_goes_here”

Authorization is the key and Token token=“” is value

December 16, 2013
0 thanks

Placing it within stack at certain level

where_you_want_it = 0 (begining of stack loaded first) Rails.application.config.middleware.insert_before(where_you_want_it, Module::Class)

December 6, 2013
0 thanks

Update the uniqueness field when it value dependent on another existent field without uniqueness restriction.

I’m using sub-transaction to update existent records on DB. I use this approach to update the uniqueness field when it value dependent on another existent field without uniqueness restriction.

Migration for uniqueness with existent dependent data in DB

class AddUniquenessBarToFoo < ActiveRecord::Migration
  class Foo < ActiveRecord::Base
  end

  def change

    add_column :foos, :bar, :string
    execute "ALTER TABLE foos ADD CONSTRAINT uk_foods_bar UNIQUE (bar)"    

    Foo.reset_column_information
    Foo.all.each do |f|
      begin
        #try get unique value in a new sub-transaction
        Foo.transaction(requires_new: true) do
          f.update_attributes!(:bar => "some ops. with another non-unique existent field to set this")
        end
      rescue ActiveRecord::StatementInvalid
         #We can't reuse a crashed transaction. New one.
         Foo.transaction(requires_new: true) do
          #Alternative unique value, if another error exist it's another
          #migration problem and then raise new error.
          f.update_attributes!(:bar => "some operation to set this-#{f.id}")
        end
      end
    end   
    change_column :foos, :bar, :string, :null => false

  end
end

Be aware about performance that is transaction per record for big DB.

December 6, 2013
0 thanks

Migration for uniqueness with existent data in DB

I’m using sub-transaction to update existent records on DB. I use this approach to update the uniqueness field when it value dependent on another existent field without uniqueness restriction.

Migration for uniqueness with existent dependent data in DB

class AddUniquenessBarToFoo < ActiveRecord::Migration
  class Foo < ActiveRecord::Base
  end

  def change

    add_column :foos, :bar, :string
    execute "ALTER TABLE foos ADD CONSTRAINT uk_foods_bar UNIQUE (bar)"    

    Foo.reset_column_information
    Foo.all.each do |f|
      begin
        #try get unique value in a new sub-transaction
        Foo.transaction(requires_new: true) do
          f.update_attributes!(:bar => "some ops. with another non-unique existent field to set this")
        end
      rescue ActiveRecord::StatementInvalid
         #We can't reuse a crashed transaction. New one.
         Foo.transaction(requires_new: true) do
          #Alternative unique value, if another error exist it's another
          #migration problem and then raise new error.
          f.update_attributes!(:bar => "some operation to set this-#{f.id}")
        end
      end
    end   
    change_column :foos, :bar, :string, :null => false

  end
end

Be aware about performance that is transaction per record for big DB.

December 3, 2013
0 thanks

usage examples

For detailed usage examples of where see “Conditions” under ActiveRecord::Base.

December 2, 2013 - (v3.2.13)
0 thanks

Redirect Status

Redirect 302

get "/accounts", :to => redirect("/", :status => 302)
November 26, 2013
0 thanks

Updated list of statuses

The list of supported statuses is now in the layout & rendering rails guide:

http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option

November 22, 2013
0 thanks
November 18, 2013
0 thanks

BEWARE of options[:value] in a partial

No problem with new records however,

the following line will not display the current @ecard value on EDIT but ‘contact@host.com’.

text_field :ecard, :sender, :value => 'contact@host.com'

Don’t let your views take control, but if you insist:

text_field :ecard, :sender, :value => f.object.ecard.blank? ? 'contact@host.com' : f.object.ecard

This doesn’t make sense, since when this object was created they deleted the default, which made it blank. Why would they want it back?

November 13, 2013 - (v3.2.13)
0 thanks

Adjacency

Just for completeness (it should behave like this), comparing ranges that start and end with the same value will overlap, e.g.

(1..5).overlaps?(5..10) # => true