first_or_create(attributes = nil, &block) public

No documentation

This method has no description. You can help the Ruby on Rails community by adding new notes.

Show source
Register or log in to add new notes.
November 6, 2014
7 thanks

Find the First Instance in the Table. If None Exists, Create One.

Specify the data you’re looking for. If it exists in the table, the first instance will be returned. If not, then create is called.

If a block is provided, that block will be executed only if a new instance is being created. The block is NOT executed on an existing record.

Code example

MyStat.where(name: statistic_name).first_or_create do |statistic|
  statistic.value = calculate_percentage
  statistic.statistic_type = "percentage"
January 22, 2016
3 thanks

Creates record by given attributes only if table is empty

This method first searches the table for ANY FIRST RECORD, not the one matching given attributes. If no record is found at all, it creates one using the specified attributes. This might be misunderstood in many cases.

March 6, 2016
2 thanks

RE: FALSE: Creates record by given attributes only if table is empty

Dino’s comment was almost certainly due to a misunderstanding of the API, a mistake I made myself the first time I used it, and one I’ve witnessed multiple others make as well.

The fact that this method takes an attributes parameter leads one to think the passed params are the criteria for the selection. At first glance it would appear it would be used like this:

User.first_or_create(email: 'derek@somwhere.com')

Where in reality this would grab the “first” record (say w/ email “john@smith.com”), and change its email to “derek@somwhere.com”, a fairly surprising action that doesn’t obviously fail, leading to some pretty subtle bugs.

In reality it should be used like this:

User.where(email: 'derek@somwhere.com').first_or_create

And the attributes param. isn’t used in 99% of use cases. (If at all - the provision for the block that executes only on create fully duplicates what the attributes parameter can do in a much more obvious way.)

IMHO this is simply a bad API that one just needs to be aware of. But it’s unfair to knock dino for what’s likely a highly common misreading.

March 23, 2016
1 thank

RE: RE: FALSE: Creates record by given attributes only if table is empty

keredson is still a little off on the behavior.

>> Where in reality this would grab the “first” record (say w/ email “john@smith.com”), and change its email to “derek@somwhere.com”, a fairly surprising action that doesn’t obviously fail, leading to some pretty subtle bugs.

This isn’t right, as if you look at the source it calls: “first || create(attributes, &block)”

So in the example of:

User.first_or_create(email: 'derek@somwhere.com')

it would find the first user with any email, and return it. And thats it. The attributes passed in as params are only used in the event that first returns no matches, and create is called.

I’m using it in a way similar to:

Foo.where(bar: baz_params[:bar]).first_or_create(baz_params)

This will find the first Foo where bar is equal to the bar sent from baz_params. If none is found, it will create it. It’s useful for me when importing large amounts of data where I know there will be duplicate records.

August 18, 2016
0 thanks

Top 10 Tools/Ruby Gems for Quickly Building Social Networking Sites

The world is social. Where art thou? In the attention-drive world, social media rules the roost. So, it is no wonder if you have been bitten by the social networking bug and want to develop a social networking site. If you are contemplating the best platform for developing a social media site, then Ruby on Rails is an ideal option. Not only, Ruby on Rails offer you rapid development, it comes packed with a horde of gems to make the work even easier. Check out some of the best Ruby gems for building social networking websites:

Read It From Here: http://goo.gl/3OVVQY

June 8, 2016
0 thanks


There are basically two levels of accessing network services in case of rails .

The socket and network libraries are such important parts of integrating Ruby applications with the Internet and other communications-based environments.

One is through socket libraries provide low level access to connection oriented and connection-less protocols. Where user can implement client and server connection. Ruby is also having Network libraries that provide users a high level access to specific network protocols like FTP,HTTP and Etc.

At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols. Ruby also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.

What are Sockets?

Sockets are basically a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. Sockets can be implemented on different channels : Unix domain sockets, TCP, UDP, and so on. The socket library mainly provides specific classes and interface for handling a transports.

A SimpleClient:

Hereis a very basic client program which will open up a connection to a given port and given host. Ruby class TCPSocket provides open function to open a socket. The TCPSocket.open(hosname, port ) opens a TCP connection to hostname & theport.

Once socket is open, you can actually read that particular thing like IO object. When it’s done, just remember to close it, as you close that file. The following code connects to a given host and port, reads any available data from the socket, and then exits:

require ‘socket’ # Socket in standard library

hostname = ‘localhost’

port = 8080

s = TCPSocket.open(hostname, port)

while line = s.gets # Gets and Read the lines from the socket

puts line.chop # And print with platform line terminator end

s.close # socket Closed

A Simple Server: To write Internet servers, we basically use this TCPServer class. A TCPServer object is a factory for TCPSocket objects. Now call TCPServer.open(hostname, port function to specify a port for your service and create a TCPServer object. Next, call the accept method of the returned TCPServer object. This particular method waits till client connects to the port you specified above, and then returns a TCPSocket object that basically represents the connection to that client.

require ‘socket’ # Get sockets from stdlib server = TCPServer.open(8080) # Socket to listen on port 8080 loop { # Servers run forever

client = server.accept       # Wait for a client to connect
client.puts(Time.now.ctime)  # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close                 # Disconnect from the client


Now run this server in background and then run above client to see the result.

March 4, 2016 - (>= v4.0.2)
0 thanks

FALSE: Creates record by given attributes only if table is empty

I very much doubt that dino’s comment was ever correct, but it certainly isn’t correct now. The behavior liantics describes is correct.

July 13, 2016
0 thanks

How to translate JavaScript strings in Rails

Rails I18n and elegant message passing to JavaScript

The process of “internationalization” usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of “localization” means to provide translations and localized formats for these bits. How I18n in Ruby on Rails Works

❝The limits of my language are the limits of my world.❞ ‒Ludwig Wittgenstein. With over 6,909 distinct languages in the world and most of them differing in so many different ways (e.g. in pluralization rules), it is difficult to provide specific tools for internalization. However, for unrestricted barriers of languages, Rails I18n API focuses on:

providing support for English and similar languages out of the box
making it easy to customize and extend everything for other languages

As part of this solution, every static string in the Rails framework – e.g. Active Record validation messages, time and date formats – has been internationalized, so localization of a Rails application means “over-riding” these defaults.

1.1 The Overall Architecture of the Library

Thus, the Ruby I18n gem is split into two parts:

The public API of the i18n frameworka Ruby module with public methods that define how the library works
A default backend (which is intentionally named Simple backend) that implements these methods

As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.

Here, the simplest way to implement internationalization in JavaScript;

a) Use the Script

<script type=”text/javascript”>
window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>

b) You can add the below code in JS file;


c) Get help from the application helper by adding the below method;

def current_translations

@translations ||= I18n.backend.send(:translations)



d) The backend needs to be initialized if it hasn’t been already.

I18n.backend.send(:init_translations) unless I18n.backend.initialized?

# now you can safely dump the translations to json

e) Invoke the below in your application.html.erb ;

<script type=”text/javascript”>

window.I18n = <%= current_translations.to_json.html_safe %>


f) To avoid having to know the current locale in JavaScript.

I18n[“alpha”][“welcome”]; Or I18n.alpha.welcome;

g) Various libraries and plugins for Internationalization & localisation:

i18next – http://github.com/i18next/i18next

I18n gem – http://github.com/svenfuchs/i18n

requirejs-i18n – http://requirejs.org/docs/api.html#i18n

Read More :http://www.railscarma.com/blog/technical-articles/how-to-translate-javascript-strings-rails/

July 19, 2016 - (v4.2.1)
0 thanks

A Detailed Look at Rails 5 Features and Changes

Rails 5 was announced by David Heinemeier Hansson(DHH), creator of Ruby on Rails Framework at RailsConf 2015 in Atlanta. Ruby 5.0.0 Beta version was released on 18th December 2015. Apart from the Rails 4, the new features are implemented in 5 version such as Action cable and improved turbolinks that can instantly improve the web development workflow. Here are the Rails 5 Features : Ruby Version Support :

Rails 5 will only work on Ruby 2.2.1 and above. The following features are the reasons for using ruby 2 or higher :

Symbol Garbage Collector

In Ruby On Rails applications, we usually pass symbols all over the place, doing this opens the possibility of DoS attacks when our memory is consumed by symbols that never get garbage collected. Ruby 2.2.0 introduced changes in its garbage collector to be able to collect symbols.

Module #prepend

Allows to do insert a module in-front of the class it was prepended.

Keyword Arguments

Ruby 2.0 introduced first-class support for keyword arguments:

def foo(bar:default’)
puts bar

foo # => ‘default’
foo(bar:baz’) # => ‘baz’
Incremental GC

This will help to reduce memory consumption by Rails applications. Deprecated code removed and Cleanup

Action Mailer

#deliver and #deliver! methods have been removed, use new methods deliver_now or deliver_later.

*_path helper in email views has been removed and use *_url.

Active Record

Protected attributes(attr_accessible) completely unsupported now.

Unsupport for activerecord-deprecated_finders gem.

ActionPack Assertions

assert_template and assigns() assertions are deprecated and moved into its own gem rails-controller-testing.


Rails 5 has introduced has_secure_token to include random token in models.

Action View

In action view, helper methods such as content_tag_for and div_for were removed from the core and moved out to a separate gem record-tag-helper.


New Turbolinks 3 solves one of the major problems of Rails. Few web apps works really slow cause it reloads the full page from server. This new Turbolinks 3 reloads only the contents of the body, it doesn’t reloads the whole page. It allows you to specify which elements to replace through partials.

Partial replacement feature, is the one of the most significant change in Rails 5. We will be able tell Turbolinks from client side that what content do we need to change/replace and what we don’t. To decide the replacement strategy in DOM, turbolinks will look for HTML5 custom attributes data-turbolinks-permanent and data-turbolinks-temporary.

We can use turbolinks.visit or Turbolinks.replace to update DOM and to trigger a replacement in the client side. Visit will issue a GET to the server to obtain the HTML that must be used to replace our DOM and replace expects from us the HTML that should be used for its operation.

The same functionalities can be triggered from the server-side with redirect_to and render, both redirect_to and render can receive change, keep and flush as options. But redirect_to can also receive turbolinks with true or false to force a redirect.

Action Cable

Action Cable is a framework, used to extend Rails via Websockets to add real-time message passing functionality. This is probably one of the best things in Rails 5. It smoothly integrates WebSockets with the rest of Rails application. Action cable makes it very easy to add realtime features to your app. The reason behind adding this feature was increasing need for such feature. It was introduced to extend Rails functionality with real time messaging utilizing WebSockets.

Action Cable offers a lot of advantages including being an open connection, extremely lightweight compared to other HTTP request. Another advantage is that once a connection made, it will remain open. Through that open line, both server and the client can communicate without reestablishing a new connection. The server and the client can use full-duplex connection of WebSocket to communicate to each other at the same time.

One disadvantage of Action Cable is its inability to cache requests. Another con of WebSocket is the support among browsers as only 70% of the browser market allows for WebSocket connections.

Additional New Features in Rails 5

#or method in ActiveRecord::Relation
#belongs_to is required by default
Active Record Attribute API
has_secure_token landed in ActiveRecord
Mysql active record adapter gets Json support
Render a template outside the controller
Better Minitest Test Runner

Rails API

It allows you to generate API – only Rails app and cleans out all the middleware which is not necessary in an app. When you create a new Rails application using new rails API, you will get the configuration which assumes you are working with JSON not with HTML.

Command to Create Rails API Application:

rails new my-app-apiapi

Render From Anywhere

All these days we have been using gems like render_anywhere to render views outside of controller. In Rails 5 you can render your views from anywhere. Along with the rendering options, there is also an option available for passing instant variables to templates.

Restart your App with a Rake Command

In Rail 5, you can restart all your apps with the command rake restart. And for migration: rails db:migrate Note that this list is not conclusive and to know more about all the changes in Rails 5, we recommend you to check out the release announcement on Rails.Org.

July 12, 2016
0 thanks

Ruby on Rails vs PHP

With more and more applications being built every day, programming languages too are becoming generic and all-purpose. Every programming language comes with its own set of specialization, and comparison between one programming languages to others may seem like a comparison between apples and oranges. However, comparison between two programming languages may offer you insights that might be crucial in your decision to go for a specific programming languages, especially when it comes to Ruby on Rails vs PHP. Since at RailsCarma, we work with both the ecosystems, we are able to understand the advantages and disadvantages of both. Here are some very simple and easy to understand comparison between Ruby on Rails and PHP.

PHP: PHP is a scripting language, used for web development to make interactive pages. The most common frameworks used for PHP are CakePHP, CodeIgnitor, Laravel, etc.

Ruby on Rails: Ruby is a scripting language and Rails is a web application framework written in Ruby.

  1. To Learn

PHP is simpler to learn as compared to Ruby especially for fresher in development. PHP codes can be easily run on server and deployed. To maintain the code, some standard needs to be followed. When it comes to frameworks, the benefit of PHP is that, it has more number of frameworks compared to Ruby. You can find more PHP developers compared to Ruby on Rails, which is really helpful for the companies or developers who need to learn the language. Documents and solutions are easily and readily available for PHP than Ruby on Rails, as applications and websites developed in PHP are more in number as compared to RoR.

  1. Resources

PHP provides lots of resources, frameworks and applications, such as WordPress, Drupal, Joomla, Magento, whereas Ruby on Rails in this department.

  1. Performance

PHP (language) is faster as compared to Ruby on Rails (framework) as it was designed only for web, but PHP is almost same or slower when it’s with frameworks like Laravel, CodeIgnitor, etc.

  1. Frameworks

Rails – The more you work on this framework, the more you will gain. It helps in providing quality products in less time when compared to PHP. Rails is a stable framework so companies and developers can easily adjust to it by learning one single framework, whereas for PHP there are a lot of frameworks which may make learning confusion. There are also no surety whether all the PHP frameworks will be supported in future or not.

  1. Development

Rails is a well-engineered framework where most of the necessary things are automated so that developer can just focus on business related work.

The points where PHP lacks are:

ScaffoldingGenerating a code in an easy and straightforward way, helps in faster development, whereas PHP lacks in this regard. However, PHP community has started work on this with FuelPHP providing similar features.
GemsRails provides plugins as a gem. Just add in your application and it fastens your development. Also, it’s easy to maintain as you are not trying to load libraries. For ex:Devise” gem which is used for authentication can be just installed in an application to handle all the processes.
ORMActiveRecord in the Ruby on Rails is the best part where you can perform all the database related queries using Ruby. Although PHP frameworks too provide the same but not up to the level of Ruby on Rails.
  1. Testing

Rails has testing frameworks that can be used to test your code and provide bug free code and make the client happy, where PHP framework are still trying to get this feature. PHPUnit is one such example.

  1. Cost

Development in PHP is much cheaper as compared to development in Ruby on Rails. Since, PHP is easier to learn and implement, it has more developers and so because of resources vs demand scale, it is cheaper to get your website developed in PHP as compared to Ruby on Rails.

Conclusion PHP has very large developer pool, it is easy to learn, has too many framework to choose, can find easy solution with the availability of experienced developers and is affordable. Ruby on Rails has passionate community, is always introducing new changes, application will be quick to market and best suits for agile development.

July 25, 2016
0 thanks

Application Performance Monitoring with New Relic

The New Relic Ruby Agent runs in one of two modes:

Production Mode Low overhead instrumentation that captures detailed information on your application running in production and transmits them to newrelic.com where you can monitor them in real time.

Developer Mode

A Rack middleware that maps /newrelic to an application for showing detailed performance metrics on a page by page basis. Installed automatically in Rails applications.

NewRelic Setup

To add ruby-agent to your project add the gem in your gemfile


Create an account in newrelic.com. You will get a 30 day free trial version

Once you signup download newrelic.yml file

Copy and paste the file in your project config folder



Bundle install (after adding gem into gemfile)

Rails 2.x without bundler

config.gemnewrelic_rpm” (In environment.rb)

After installation of newrelic go to the newrelic.yml and look into it by default you will get

Development, test, staging and production environments

You can change/add the environment name like staging can change it to uat.

You can find developer_mode only for development environment, so what is developer_mode?


New Relic Agent will present performance information on the last 100 transactions you have executed since starting the mongrel

NOTE: There is substantial overhead when running in developer mode (Do not use for production or load testing.)

To view the performance information including SQL statement

localhost:3000/newrelic (If your application is running in port 3000)

Set the application name for your required environment, so that the application name will be appearing on your newrelic dashboard and it will be easy to monitor without the name ambiguity

For example:


<<: *default_settings

monitor_mode: true

app_name: Sample_Project

So when you open NewRelic dashboard you can find Sample_Project under Name column, click on it to see all the transactions.

Advantage of NewRelic Monitoring:

The main advantage of newrelic is Application Performance Management (APM).
New Relic APM is the only tool you’ll need to see everything in your Ruby application from the end user experience to server monitoring. Trace slow database queries, 3rd party APIs and web services, caching layers, background jobs, and more. Ruby monitoring has never been easier.
Error Rate: the agent collects and reports all uncaught exceptions by default.
Transaction history with graphs.
SQL Query in Transaction block.
You can also find most time consuming methods, what is making it slow.
You can also trace background-jobs.
Every time you’re working on the performance of your application, it’s always good to know what kind of effect does a particular deploy has on the performance of the application. To understand the effect, you can notify New Relic when you are performing a deployment. This way if performance degrades or improves by setting key transactions, you will get to know and then measures could be taken to improve the performance.

Newrelic is a complete tool to monitor your application and quickly response on the errors and help in serving end users in an optimized way. http://www.railscarma.com/blog/technical-articles/application-performance-monitoring-with-new-relic/