<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ruby on rails &#8211; redpanthers.co</title>
	<atom:link href="/tag/ruby-on-rails/feed/" rel="self" type="application/rss+xml" />
	<link>/</link>
	<description>Red Panthers - Experts in Ruby on Rails, System Design and Vue.js</description>
	<lastBuildDate>Mon, 29 Apr 2019 11:28:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.2.7</generator>
	<item>
		<title>Upgrading to Rails 5.1x</title>
		<link>/upgrading-to-rails-5-1x/</link>
				<pubDate>Wed, 21 Mar 2018 08:14:20 +0000</pubDate>
		<dc:creator><![CDATA[tony]]></dc:creator>
				<category><![CDATA[Rails 5.1]]></category>
		<category><![CDATA[5.1.x]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[tony vincent]]></category>
		<category><![CDATA[upgrade]]></category>

		<guid isPermaLink="false">http://redpanthers.co/?p=16171</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[Rails 5.1rolled out with some major changes and features including


<ul>
 	

<li>Yarn and webpack support</li>


 	

<li>Dropped JQuery as a default dependency</li>


 	

<li>Built-in support for writing system tests using Capybara</li>


 	

<li>Encrypted secrets</li>


</ul>


and many more, you can find the detailed release notes <a href="http://edgeguides.rubyonrails.org/5_1_release_notes.html">here</a>. Recently we upgraded one of our production apps to 5.1x and since we have good test coverage, upgrading was mostly painless. We still had to make some minor changes down the road


<h3>1. No more <code>before_filter</code></h3>


One of our controllers still had the old-fashioned `before_filter` and we encountered the following error while booting up


<p class="p1"><code>undefined method 'before_filter' before_filter has been deprecated in Rails 5.0 and removed in 5.1.</code></p>


This is because `before_filter` and <code>after_filter</code> are <a href="https://github.com/rails/rails/blob/v5.0.0.beta2/actionpack/lib/abstract_controller/callbacks.rb#L190-L193">deprecated</a> from Rails 5.0.0 onwards. As you might have guessed, changing from <code>before_filter</code> to <code>before_action</code> is the solution here.
&nbsp;


<h3>2. <code>halt_callback_chains_on_return_false</code> is deprecated</h3>


We saw the following deprecation warning in our logs after the update


<p class="p1"><code>ActiveSupport.halt_callback_chains_on_return_false= is deprecated and will be removed in Rails 5.2.</code></p>


From Rails 5.0x, the <a href="https://github.com/rails/rails/pull/17227">callback chain is <span class="x x-first x-last">not </span>halted when a before callback returns false</a>. We need to use <code class="highlighter-rouge">throw(:abort)</code> to explicitly halt callbacks
Though we had no return false in our callbacks, we still had to remove the line,
<code>ActiveSupport.halt_callback_chains_on_return_false = false</code> from <code>config/initializers/new_framework_defaults.rb</code> to get rid of the warning.
&nbsp;


<h3>3. Passing a class to the <code>class_name</code> is deprecated</h3>


One of the deprecation warnings after the update was,


<pre class="nums:false lang:default decode:true">Passing a class to the 'class_name' is deprecated and will raise an ArgumentError in Rails 5.2.
It eagerloads more classes than necessary and potentially creates circular dependencies. Please pass the class name as a string:
</pre>




<p class="p1">This warning message was due to passing a class to `class_name` option when specifying associations &#8211; this is <a href="https://github.com/rails/rails/commit/8312a0d22212798864f142b5a94805e0baa6c562">no longer recommended</a><span class="hljs-string">&#8216;</span></p>




<pre class="nums:false lang:default decode:true">- has_one :contact, class_name: UserContact
+ has_one :contact, class_name: 'UserContact
</pre>


passing class name as a string is a standard now
Happy Hacking <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/2764.png" alt="❤" class="wp-smiley" style="height: 1em; max-height: 1em;" />
&nbsp;


<hr />
PS: If you need any help in upgrading your rails version drop an email to us at <strong>info@redpanthers.co </strong>or<strong> upgrade@redpanthers.co. </strong>We will be more than happy to go through your system and give a <strong>free upgrade action plan and estimation </strong>.]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>Rails Generators</title>
		<link>/rails-generators/</link>
				<pubDate>Mon, 18 Sep 2017 17:27:20 +0000</pubDate>
		<dc:creator><![CDATA[anjana]]></dc:creator>
				<category><![CDATA[Beginners]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=1441</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[Rails generators are used to create many files for models, controllers, views, unit tests, migrations and more. It will do some of the manual work for us. So it saves time. They can also be used to set up some basic specs for the application test suite.
Running <tt>rails generate(or rails g)</tt> by itself gives a list of available generators:


<pre class="lang:sh decode:true">$ rails generate
Usage: rails generate GENERATOR [args] [options]
...........
Rails:
assets
channel
controller
generator
helper
integration_test
jbuilder
job
mailer
migration
model
resource
responders_controller
scaffold
scaffold_controller
task
.............</pre>


The main generators that rails offers are:


<ul>
 	

<li>controller: The Rails controller coordinates the interaction between the user, the views, and the model.</li>


 	

<li>helper: Code in helpers is included in the corresponding view. We can move big loops, method calls or other logic into a method in the helper.</li>


 	

<li>mailer: It allows for sending and receiving emails from and to your application.</li>


 	

<li>migration: Rails Migration allows you to use Ruby to define changes to your database schema.</li>


 	

<li>model: It is Ruby class that talk to the database, store and validate data, perform the business logic.</li>


 	

<li>scaffold: It refers to the auto-generation of a simple set of a model, views and controller usually for a single table.</li>


</ul>


Following is the list of options, which can be used along with generators:


<p style="padding-left: 30px;">-h, [&#8211;help] # Print generator&#8217;s options and usage
-p, [&#8211;pretend] # Run but do not make any changes
-f, [&#8211;force] # Overwrite files that already exist
-s, [&#8211;skip] # Skip files that already exist
-q, [&#8211;quiet] # Suppress status output</p>




<h2>Generators</h2>


You can create different generators by running <em>rails g</em> in the terminal. Let&#8217;s have a look at each of them.


<ul>
 	

<li>rails generate model ModellName</li>


</ul>




<p style="padding-left: 60px;">It generates the model and the associated database table. For example, we can add a new model to the app called User with fields name and age as,</p>




<p style="padding-left: 60px;">Eg:  rails g model User name: string age: integer</p>




<ul>
 	

<li>rails generate controller ListController show edit</li>


</ul>




<p style="padding-left: 60px;">It generates controller. It is used if you are creating static views or non-CRUD related features. Let&#8217;s create a user controller that will manage the data flow and view for each users.</p>




<p style="padding-left: 60px;">Eg:  rails g controller users</p>




<ul>
 	

<li>rails generate scaffold ModelName ControllerName</li>


</ul>




<p style="padding-left: 60px;">Generates Scaffold. Let&#8217;s create a scaffold User with edit and view actions.</p>




<p style="padding-left: 60px;">Eg:  rails g scaffold User edit view</p>




<ul>
 	

<li>rails generate migration AddNewTable</li>


</ul>




<p style="padding-left: 60px;">Generates Table to migrate. We can create migration for adding a table as</p>




<p style="padding-left: 60px;">Eg:  rails g migration User</p>




<ul>
 	

<li>rails generate plugin PluginName</li>


</ul>




<p style="padding-left: 60px;">Generates Plugin.</p>




<p style="padding-left: 60px;">Eg:  rails g plugin rails_plugin</p>




<ul>
 	

<li>rails generate integration_test TestName</li>


</ul>




<p style="padding-left: 60px;">Generates Integration Test.</p>




<p style="padding-left: 60px;">Eg:  rails generate integration_test User</p>




<ul>
 	

<li>rails generate session_migration</li>


</ul>




<p style="padding-left: 60px;">Generates Session Migration.</p>




<h2 id="creating-generators-with-generators">Creating Generators with Generators</h2>


Generators themselves have a generator:


<pre class="lang:ruby decode:true">$ rails generate generator initializer
 create lib/generators/initializer
 create lib/generators/initializer/initializer_generator.rb
 create lib/generators/initializer/USAGE
 create lib/generators/initializer/templates</pre>


This is the generator just created:


<pre class="lang:default decode:true">class InitializerGenerator &lt; Rails::Generators::NamedBase
  source_root File.expand_path("../templates", __FILE__)
end</pre>




<p class="">First, notice that we are inheriting from <tt>Rails::Generators::NamedBase</tt> instead of <tt>Rails::Generators::Base</tt>. This means that our generator expects at least one argument, which will be the name of the initializer.</p>




<h2>Customizing Rails generators</h2>


We can customize it in, <code>config/application.rb</code>


<pre class="lang:ruby decode:true">config.generators do |g|
  g.orm :active_record
  g.template_engine :erb
  g.test_framework :test_unit, fixture: false
  g.stylesheets false
  g.javascripts false
end</pre>


So by doing the above steps will stop generating stylesheet, JavaScript, and test fixture files. We can avoid generation of unwanted files from doing these steps.
I hope this article help you in some way to know about rails generators.


<h2>References</h2>




<ul>
 	

<li><a href="https://learn.co/lessons/rails-generators-readme">https://learn.co/lessons/rails-generators-readme</a></li>


 	

<li><a href="https://www.tutorialspoint.com/ruby-on-rails/rails-generators.htm">https://www.tutorialspoint.com/ruby-on-rails/rails-generators.htm</a></li>


 	

<li><a href="http://www.agmprojects.com/blog/building-a-rails-generator-and-packing-it-into-a-gem">http://www.agmprojects.com/blog/building-a-rails-generator-and-packing-it-into-a-gem</a></li>


</ul>

]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>Chartkick: data visualization made easy with Ruby</title>
		<link>/chartkick-data-visualization-easy-ruby/</link>
				<comments>/chartkick-data-visualization-easy-ruby/#comments</comments>
				<pubDate>Wed, 18 Jan 2017 13:11:11 +0000</pubDate>
		<dc:creator><![CDATA[govind]]></dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Chartkick]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[gem]]></category>
		<category><![CDATA[graphs]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=975</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[Recently, I've been using Highcharts, Google charts and Chart Js for visualizing dynamic data in my projects. But it was difficult to integrate it with the rails application. However, for every problem in Ruby, there is a gem out there to save your day and Chartkick, a Ruby gem exclusively available for data visualization is truly a savior. Chartkick can work with Highcharts, Chart.js and Google charts to create dynamic and interactive charts that draw data from the Rails application. And the best part, you just need to write one single line of Ruby code. Isn't that amazing and powerful!
Let's begin with Installation
For installation, all you have to do is adding this line to your application's Gemfile:


<pre class="">gem &#8220;chartkick&#8221;</pre>


Then you have to choose your charting library.
In case, if more than one charting library is loaded, choose between them with the following code:


<pre class="lang:xhtml decode:true">&lt;%= line_chart data, adapter: "google" %&gt; &lt;!-- or highcharts --&gt;</pre>


P.S:- highcharts is the default adapter is nothing else is defined.
Using Chartkick
Once it&#8217;s installed, you can start playing around with chartkick. For example:


<pre class="lang:xhtml decode:true">&lt;%= line_chart User.group_by_day(:created_at).count %&gt;
</pre>




<p class="">In the above example, I have just shown you how we can make a line chart.Similarly, you can create Pie chart, Column chart, Bar chart, Area chart, Scatter chart, Geo charts, Timeline(Google Charts)etc. All you need is that one line of Ruby code. Cool, isn&#8217;t it!!</p>


Chartkick gives you a variety of options to make your charts interesting. You can also set a Global option for each chart by using initializers and even customize the HTML. Data can be passed as a Hash or as an Array. You can find more details about using Chartkick options, sending data in <a href="http://chartkick.com/">Chartkick documentation</a>.
Now, let&#8217;s have some real fun by using Chartkick to create some interactive <strong>Graphs, </strong>using<strong> Dynamic data</strong>.
To create a graph which drives data from the ajax request, you just need to define a method in the controller and pass the JSON data. For example
<em>app/controllers/views_controller.rb:</em>


<pre class="lang:ruby decode:true">class ViewsController &lt; ApplicationController
  def show
    @view = View.all
  end
  def views_by_day
    render json: View.group_by_day(:viewed_at, format: "%B %d, %Y").count
  end
end</pre>


Next, add in the code listed below to your views/show view.
<em>app/views/views/show.html.erb:</em>


<pre class="lang:xhtml decode:true">&lt;div class="container"&gt;
  &lt;h3&gt;Views By Day&lt;/h3&gt;
  &lt;%= line_chart views_by_day_view_path %&gt;
&lt;/div&gt;</pre>


We can also create graphs with Multiple Series with the below codes


<pre class="lang:xhtml decode:true">&lt;%= line_chart @.map { |view|
 {name: view.name, data: view.feats.group_by_week(:created_at).count}
} %&gt;</pre>


or


<pre class="lang:xhtml decode:true">&lt;%= line_chart Feat.view(:view_id).group_by_week(:created_at).count %&gt;
</pre>


Voila! there you have it how you want.
Here is an example charts I got for you
<a href="https://redpanthers.co/wp-content/uploads/2017/01/Chartkick.js.png"><img class="alignleft wp-image-1498 size-full" src="https://redpanthers.co/wp-content/uploads/2017/01/Chartkick.js.png" alt="Chartkick" width="541" height="746" /></a>
So, next time if you want to create charts and graphs easily in your web application, don&#8217;t forget to use <strong>Chartkick </strong>and let me know in the comment section if you know any such tool that made your coding a bliss!
Happy Coding!


<h2>References</h2>




<ul>
 	

<li><a href="http://chartkick.com/">http://chartkick.com/</a></li>


 	

<li><a href="https://ankane.github.io/chartkick.js/examples/">https://ankane.github.io/chartkick.js/examples/</a></li>


</ul>

]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/chartkick-data-visualization-easy-ruby/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
							</item>
		<item>
		<title>Optimising PostgreSQL database query using indexes</title>
		<link>/optimising-postgresql-database-query-using-indexes/</link>
				<comments>/optimising-postgresql-database-query-using-indexes/#comments</comments>
				<pubDate>Thu, 11 Aug 2016 10:59:22 +0000</pubDate>
		<dc:creator><![CDATA[coderhs]]></dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[B Tree]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[GIN]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[migration]]></category>
		<category><![CDATA[multi column]]></category>
		<category><![CDATA[partial migration]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[single column]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[training]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=389</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[At Red Panthers PostgreSQL is our go to database we use it everywhere. So thinking about how to optimize our database performance is one of the most talked about topic at our office. The best way to speed up report generation and data retrieval within a rails application is to leave it to the database, as they have algorithms and optimizations build just for that. We always felt that most Ruby on Rails projects out there, do not use the full potential of a database and they usually just limit it to a data store. PostgreSQL or any database for that matter is much more than that.
We would be blogging on how we use PostgreSQL in our projects to speed up our client's applications. This particle is the first part of a series of article we would be writing on database optimization.
<img class="aligncenter" src="http://i.imgur.com/YSZE83d.jpg?1" width="231" height="172" />
<strong>Database Indexes:</strong>
Indexes are a special lookup table that the database search engine can use to speed up data retrieval. An Index is similar to a pointer to a particular row of a table. As a real world example, consider a Britannica Encyclopedia with 22 volumes of books, and an extra book listing  the index,with which you can find out the item you are searching for in those 22 books.
PostgreSQL 9.5, provides several index algorithms like B-tree, Hash, GiST, SP-GiST and GIN. When you create an index using Ruby on Rails migration, by <strong>default it would be using the B-Tree</strong> migration. Whereas, as we move on to the indexing algorithms, we need to check into the general classification of an index and the data to be indexed.
<strong>Primary Keys</strong>
In rails, when we generate a model , by default an ID column would be added to the table. It would have integers values and they would be unique as well. By default, when you set a column as a primary key, the database would build a <em><strong>unique index </strong></em>on it. So we don&#8217;t need to add migration for it.
<strong>Foreign Keys</strong>
When you build a relationship between two tables you add a <code>foreign_key</code> in the child table to point to parent, eg: <code>user_id</code>, <code>group_id</code>. We need to query through this relationship a lot in rails, for example to load all the comments of post or all members of a group.<strong> So we need to index that for speed.</strong>.
If you are using some non id value to reference a table, lets say in your application ,you give all your users a unique URL which has the username. (Eg: http://csnipp.com/coderhs), in that case we would be using the username to query the data, so we need to have it indexed. In fact you should index all the columns you might be using in your where queries. Like if you are searching for users of a particular age or income frequents in your reports, then you should create an index for them as well.
<strong>Note:</strong>  What we explained above are single column indexes and multi column indexes. So if you are indexing just a single column in a table, its single column indexes.


<pre class="lang:pgsql decode:true">CREATE INDEX index_name
ON prices (user_id);</pre>


Rails code:


<pre class="lang:ruby decode:true">add_index :prices, :user_id</pre>


When we index multiple columns, they are called multi column index.


<pre class="lang:pgsql decode:true">CREATE INDEX index_name
ON user_views (user_id, article_id);</pre>


Rails code:


<pre class="lang:ruby decode:true">add_index :user_views, [:user_id, :article_id]</pre>


If you are joining two tables, using a column (which is not the already indexed foreign key) then you should index that as well.
<strong>State column &amp; Boolean column</strong>
State and Boolean column are columns that should be indexed as there would be a lot of rows but only limited number of values in those columns. Boolean column would have only true or false (two values)and state columns will have more than two like eg: draft, published, pending. The speed of load would be faster for these columns as they are only limited keys that can be placed in the index, and on a single lookup we can load them.
<strong>Partial indexes</strong> can be used in the above case, as the name suggests it&#8217;s an index over a subset of your table. The index would be building if it satisfies certain conditions. They can be most useful <strong>while writing scopes in rails. </strong>Lets say that you have a scope that picks up all the articles which are marked as SPAM. In your model you will write a scope like below


<pre class="lang:ruby decode:true">scope :articles, where(:spam =&gt; 'true')</pre>


So internally it&#8217;s a where query, one can add a partial index migration as follows:


<pre class="lang:pgsql decode:true">CREATE INDEX index_name
on articles (spam is true);</pre>


Rails:


<pre class="lang:ruby decode:true">add_index :articles, :spam, name: "index_articles_on_spam", where: "(spam IS true)"</pre>


<strong>When not to use indexes</strong>
Using indexes speeds up the SELECT and WHERE command, but it does slows down the execution of INSERT.
<strong>So avoid indexing when we have table that has a lot of insert and update</strong>
So we should avoid using Indexes when we have a table that holds a huge number of raw data, where we do a lot of batch updates and insert. For example, in an IoT application we would pipe all the data from multiple devices to a single table , summarize  and insert it into its proper tables. And  by a lot of data, I am referring to at least 10+ MB of data per minute. In most cases, we would just truncate that table after processing, hence it would slow us down if we were to index it.
<strong>If the table is too small and you know it will always be small</strong>
If you have a setting table which just stores the application settings, that can be modified by an admin panel. Then it doesn&#8217;t seem to be worth having an index there.
<strong>When you are manipulating the values of a column a lot</strong>
Lets say the particular value of a column gets changes extremely a lot, like the website view count. Then indexing it is not highly recommended.
Finally to complete this article. If you want to drop an index:
SQL


<pre class="lang:pgsql decode:true">DROP INDEX index_name;</pre>


Rails


<pre class="lang:ruby decode:true">remove_index :books, :created_at</pre>


<strong>Summary</strong>:


<ul>
 	

<li>Index Primary key</li>


 	

<li>Index Foreign key</li>


 	

<li>Index all columns you would be passing into where clause</li>


 	

<li>Index the keys used to Join tables</li>


 	

<li>Index the date column (if you are going to call it frequent, like rankings of a particular date)</li>


 	

<li>Index the type column in an STI or polymorphism.</li>


 	

<li>Add partial index to scopes</li>


 	

<li>Do not index tables with a lot of read, write</li>


 	

<li>Do not index tables you know that will remain small, all through out its life time</li>


 	

<li>Do not index columns where you will be manipulating lot of its values.</li>


</ul>


Keep visiting here to know more about the PostgreSQL indexing algorithms in part 2 of this article.
<strong>References:</strong>
<a href="https://www.postgresql.org/docs/9.2/static/indexes-types.html">https://www.postgresql.org/docs/9.2/static/indexes-types.html</a>
<a href="http://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html">http://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html</a>
<a href="http://www.tutorialspoint.com/postgresql/postgresql_indexes.htm">http://www.tutorialspoint.com/postgresql/postgresql_indexes.htm</a>]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/optimising-postgresql-database-query-using-indexes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>Database transaction in Rails</title>
		<link>/database-transaction-rails/</link>
				<pubDate>Mon, 01 Aug 2016 11:38:48 +0000</pubDate>
		<dc:creator><![CDATA[coderhs]]></dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DBA]]></category>
		<category><![CDATA[expert]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[nested transaction]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[transaction]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=377</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[

<blockquote>A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties called the <strong>atomicity</strong>, <strong>consistency</strong>, <strong>isolation</strong> and <strong>durability</strong> (<strong>ACID</strong>) properties, to qualify as a transaction.</blockquote>


We use database transactions to make sure that all the instructions we send to database are successful, and would cause changes to the database only if they are successful. Let&#8217;s say that you are working on a banking application which would withdraw money from one account and deposit into another account. The code for it would look like below


<pre class="lang:ruby decode:true">User.find(156).withdraw(1000)
User.find(157).deposit(1000)</pre>


But for some reason, the withdrawal was successful but the deposit was not, the amount was taken out but never deposited to the other user.To avoid these kind of issues, database has a functionality called transactions, in which you can  build up each sql query. But if for any reason, any of the sql statements fails or an exception rises in the block, all the transactions are rolled back to their original form.


<pre class="lang:default decode:true">User.transaction do
  User.find(156).withdraw(1000)
  User.find(157).deposit(1000)
end</pre>


In rails, the transaction method is available as class method and instance method, but the functionality for both is same. There is no difference when you will use.


<pre class="lang:default decode:true">@user.transaction do
end</pre>


and


<pre class="lang:default decode:true">User.transaction do
end</pre>


The reason why rails provides this, is for better readability.
One can also mix various model types in a transaction, as the transaction are bound to a database connection. So there is no issue in writing code like below.


<pre class="lang:default decode:true">User.transaction do
  Order.create order_attributes
  Purchase.create purchase_attribute
end</pre>


&nbsp;
<strong>Nested Transactions: </strong>It is possible to write nested transactions. But it is to be noted that,<strong> it would just make each child transaction a part of the parent transaction</strong>. Taking the example from the Rails documentation.
The below code


<pre class="lang:default decode:true">User.transaction do
  User.create(username: 'Kotori')
  User.transaction do
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end</pre>


Creates both “Kotori” and “Nemu”. Reason is the ActiveRecord::Rollback exception in the nested block does not issue a ROLLBACK. Since these exceptions are captured in transaction blocks, the parent block does not see it and the real transaction is committed.
Reference:
https://technet.microsoft.com/en-us/library/ms190612(v=sql.105).aspx]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>Skip unnecessary files while running Rails Generate</title>
		<link>/customize-rails-auto-generation/</link>
				<pubDate>Wed, 27 Jul 2016 04:27:04 +0000</pubDate>
		<dc:creator><![CDATA[coderhs]]></dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[coffee]]></category>
		<category><![CDATA[customize]]></category>
		<category><![CDATA[generators]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[speed up development]]></category>
		<category><![CDATA[Tip]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[training]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=354</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[Rails Generate is one of the features provided by Rails that would speed up the application development. However, we won't be needing all the files generated by rails when running the generate command.
For example:
<code>rails generate controller Home Index new create</code>,  would create the following set of files:
<a href="https://redpanthers.co/wp-content/uploads/2016/07/before_altering_the_generator.png"><img class="alignnone size-full wp-image-356" src="https://redpanthers.co/wp-content/uploads/2016/07/before_altering_the_generator.png" alt="before_altering_the_generator" width="488" height="312" /></a>
As one knows from experience, the helper; javascript and stylesheet files are not always used. In fact, most of the time, we would have a single stye.scss, and main.coffee that would take care of 95% of the total behaviour of our application. So, if we do not delete those files after generation, we would just end up with a lot of files in our system which would have no code throughout the life cycle of the program.
Fortunately, rails gives us the ability to customize its own generators so that we can disable these files from being generated. Once we place the below code in the <code> application.rb</code>, it will stop the generation of these extra files.


<pre class="toolbar:2 show-plain:3 lang:ruby decode:true ">config.generators do |g|
  g.helper false
  g.stylesheets false
  g.javascripts false
  g.view_specs false
end</pre>


Now, when you run <code>rails generate controller Home Index new create</code>, you will get less files.
<a href="https://redpanthers.co/wp-content/uploads/2016/07/after_altering_generators.png"><img class="alignnone size-full wp-image-355" src="https://redpanthers.co/wp-content/uploads/2016/07/after_altering_generators.png" alt="after_altering_generators" width="482" height="219" /></a>]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>Counter Cache:  How to get started</title>
		<link>/counter-cache-how-to-get-started/</link>
				<pubDate>Tue, 26 Jul 2016 10:40:48 +0000</pubDate>
		<dc:creator><![CDATA[coderhs]]></dc:creator>
				<category><![CDATA[Beginners]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[counter]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[improvement]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[oracale]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[training]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=335</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[Displaying the <em>number of tasks under a projec</em>t or the <em>number of comments in a post</em> or the <em>number of users in an organization or anything </em>similar is a common requirement in most rails applications. The code for doing it is also simple- <strong>@project.tasks.count;</strong> but the problem with this code is that every time you run it, you are counting the number of tasks of that project one by one. So, the speed of execution decreases with more number of rows. This code will slow down your page load, if you are displaying the details of more than one project in your page as shown below.
<a href="https://redpanthers.co/wp-content/uploads/2016/07/Screen-Shot-2016-07-26-at-2.10.14-PM.png"><img class="size-full wp-image-338" src="https://redpanthers.co/wp-content/uploads/2016/07/Screen-Shot-2016-07-26-at-2.10.14-PM.png" alt="project_list" width="198" height="123" /></a>
To speed this up, rails gives you an in-build mechanism called &#8220;<a href="http://guides.rubyonrails.org/association_basics.html"><strong>Counter Cache</strong></a>&#8220;. As the name suggests, it literally means to cache the number of referenced rows it has (number of tasks a project has).
<strong>Example code definition</strong>


<pre class="toolbar:2 toolbar-overlay:false toolbar-hide:false toolbar-delay:false show-title:false show-lang:2 plain:false show-plain:3 plain-toggle:false popup:false lang:ruby decode:true">class Projects &lt; ActiveRecord::Base
  has_many :tasks
end
class Task &lt; ActiveRecord::Base
  belongs_to :project
end</pre>


To implement counter_cache, you need to pass in the <strong>counter_cache: true </strong>option along with the belongs_to relationship. You also need to add a migration to add an extra column called <strong>tasks_count</strong> to store the count. This needs to be added to the other model, which has the <strong>has_many</strong> reference.


<pre class="toolbar:2 plain:false show-plain:3 plain-toggle:false popup:false lang:ruby decode:true ">class Task &lt; ActiveRecord::Base
  belongs_to :project, counter_cache: true
end</pre>


<strong>Migration</strong>


<pre class="toolbar:2 show-plain:3 lang:default decode:true">class AddTasksCounterCacheToProjects &lt; ActiveRecord::Migration[5.0]
  def change
    add_column :projects, :tasks_count, :integer
  end
end</pre>


If you are adding counter cache to an existing system, you need to update your <strong>tasks_count </strong>with the existing counts. To do that, one can use the code given below. Either place the code along with the migration or run it in console in both production/development environments.


<pre class="toolbar:2 show-plain:3 lang:ruby decode:true">Project.find_each { |project| Project.reset_counters(project.id, :tasks) }
</pre>


<span style="line-height: 1.5;">Also note that the tasks_count is just the default column name; if you wish to change it with another name, just pass that name along with the :counter_cache option as below.</span>


<pre class="toolbar:2 show-plain:3 lang:ruby decode:true  ">class Task &lt; ActiveRecord::Base
  belongs_to :project, counter_cache: :not_the_default_column_name
end</pre>


Now, to use the counter cache in your calculations, you should use the method &#8220;size&#8221; instead of &#8220;count&#8221;. The method &#8220;size&#8221; will use the counter_cache if its present, where as using &#8220;.count&#8221; itself would do the actual sql count.


<pre class="toolbar:2 show-plain:3 lang:ruby decode:true">&lt;% Project.all.each do |project| %&gt;
  &lt;%= project.name %&gt; (&lt;%= project.tasks.size %&gt;)
&lt;% end %&gt;
</pre>


<span style="line-height: 1.5;"><strong>Points to Remember</strong></span>


<ul>
 	

<li><strong>:counter_cache</strong> is the optional attribute of a <strong>belongs_to</strong> relationship</li>


 	

<li>It requires the creation of an extra column (tasks_count) in the table which has the <strong>has_many</strong> relationship</li>


 	

<li>One can use another column name by passing the name along with :counter_cache option</li>


 	

<li>To use the counter_cache, one must use the <strong>&#8220;.size&#8221;</strong> method</li>


</ul>


<strong>Speed Improvements</strong>
<a href="https://redpanthers.co/wp-content/uploads/2016/07/speed_with_count.png"><img class="alignnone wp-image-339 size-full" src="https://redpanthers.co/wp-content/uploads/2016/07/speed_with_count.png" alt="Speed with just count" width="797" height="73" /></a>
<a href="https://redpanthers.co/wp-content/uploads/2016/07/speed_with_counter_cache.png"><img class="alignnone wp-image-340 size-full" src="https://redpanthers.co/wp-content/uploads/2016/07/speed_with_counter_cache.png" alt="speed_with_counter_cache" width="776" height="53" /></a>
&nbsp;]]&gt;		</p>
]]></content:encoded>
										</item>
	</channel>
</rss>
