Pages

Showing posts with label Rails 4. Show all posts
Showing posts with label Rails 4. Show all posts

Monday, June 1, 2015

Check if ActiveRecord object is valid with params before updating to Database

To update the attributes without saving them, you can use
@obj.assign_attributes( params[:obj] )
Then to check if the object is valid, you can call
@obj.valid?
If the object is not valid, you can see the errors (only after calling .valid?) by calling
@obj.errors
If the object is valid, you can save it by calling
@obj.save
However, all of this usually isn't necessary. If the object isn't valid, then ActiveRecord won't save the object to the database, so all of the attribute changes are forgotten when you leave the controller action.
Also, since an invalid record won't be saved to the database, you can always just call Object.find() again to get the original object back.

Wednesday, March 18, 2015

Adding Layouts to Devise Views

Add following code to your Devise.rb file

# append to end of config/initializers/devise.rb
Rails.application.config.to_prepare do
  Devise::SessionsController.layout "devise"
  Devise::RegistrationsController.layout proc { |controller| user_signed_in? ? "application" : "devise" }
  Devise::ConfirmationsController.layout "devise"
  Devise::UnlocksController.layout "devise"
  Devise::PasswordsController.layout "devise"
end

Wednesday, January 14, 2015

Fetch a Average Color from an Image

One can fetch a average color from an image using Rmagick with the below snippet.

img =  Magick::Image.read("http://SOME_IMAGE_URL").first
pix = img.scale(1, 1)
avg_color_hex = pix.to_color(pix.pixel_color(0,0)
It will return the Color code(The maximum color used in that image).

Wednesday, December 10, 2014

Model Concerns in Rails 4

Concerns in Model can be used to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:


Consider a Article model, a Event model and a Comment Model. A article or A event has many comments. A comment belongs to either article or event.
Traditionally, the models may look like this:
Comment Model:
class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
  has_many :comments, as: :commentable 

  def find_first_comment
    comments.first(created_at DESC)
  end

  def self.least_commented
   #return the article with least number of comments
  end
end
Event Model
class Event < ActiveRecord::Base
  has_many :comments, as: :commentable 

  def find_first_comment
    comments.first(created_at DESC)
  end

  def self.least_commented
   #returns the event with least number of comments
  end
end
As we can notice, there is a significant piece of code common to both Event and Article Model. Using concerns we can extract this common code in a separate module Commentable.

Friday, November 21, 2014

Simple, user-friendly cancel links for your Rails forms



The default Rails view generator includes back links on form-related view templates, so if users change their mind they can easily get out of the form and on to something else. However, these links are static. What do you do if you allow users to access the form from multiple views (say, an index and a show).
Here’s a simple but effective solution I came up with: Instead of passing a static URL, I pass the HTTP referrer environment variable as the location. That way users are taken back to the page from which they opened the form to begin with.
Here’s how it works. Most of the code resides in the application_helper.rb file:
  module ApplicationHelper
    include Rails.application.routes.url_helpers

    def cancel_link
      return link_to 'Cancel', request.env["HTTP_REFERER"], 
        :class => 'cancel', 
        :confirm => 'Are you sure? Any changes will be lost.'
    end
  end
You’ll need to include Rails.application.routes.url_helpers in order to access link_to from a helper method. Then you add the helper method itself, which does nothing more than return a cancel link. Mine uses an old-style :confirm message; you can spruce it up with some less obtrusive if you’d like.
If I need a cancel link in a view, I just add
  <%= cancel_link %>
The result: a flexible, reusable cancel option that’s much more user-friendly.

Monday, May 12, 2014

Irreversible Migrations in Ruby on Rails

In Rails 2 in migrations there were only 2 methods: up and down. They are called on running migrations up and down respectively with rake tasks rake db:migrate and rake db:rollback.

In Rails 2

def up
add_column :users, :active, :boolean User.update_all(active: true) end

def down remove_column :users, :active end

Rails 3 produced us great method change which allowed us to write there code which creates a table and drops the table automatically on rolling migration back. But unfortunately there was a problem – you didn’t have opportunity to say “don’t run this peace of code on down but run this only on up”. So the solution was just to use old syntax. 

Tuesday, January 7, 2014

Not Equal support for Active Record queries in Rails 4

The Active Record query interface for the most part abstracts SQL from the developer. However, there is a condition that always requires using pure string conditions in awhere clause: <> or !=, depending on the database. Starting in Rails 4, query method not has been added to rectify this.

Example

Let's look at an example of executing the new not query method. First we will look at how it was done in Rails 3, and then look at how Rails 4 handles the same problem. All examples will be querying against an Article model with a title field. The examples below will be using a SQLite database.

The Rails 3 Way

Article.where("title != ?", params[:title])

The Rails 4 Way

To use the new query method, it must be chained to a where clause with no arguments:
Article.where.not(title: 'Rails 3')
# >> SELECT "articles".* FROM "articles" WHERE ("articles"."title" != 'Rails 3')
The not query method can also accept an array to ensure multiple values are not in a field:
Article.where.not(title: ['Rails 3', 'Rails 5'])
# >> SELECT "articles".* FROM "articles" WHERE ("articles"."title" NOT IN ('Rails 3', 'Rails 5'))

Monday, January 6, 2014

New HTML5 Form Input Helpers for Rails4

In this post, we are going to take a look at the new HTML5 Form Helpers being added into Rails 4. While we are only covering the model object helper versions that are used with form_for, each form helper below also has a corresponding tag helper. For example, if we are talking about week_field, there is a tag helper week_field_tag that can be used withform_tag.

week_field

The week_field form helper creates an input of type "week", that sets a week without any timezone information. A week is represented by four digits for the year, followed by -W, and ending with two digits representing the week number. For example, the current week of this post would be 2012-W50.
The week_field form helper accepts three options: :min, :max, and :step:
  • :min: The minimum acceptable value
  • :max: The maximum acceptable value
  • :step: The acceptable value granularity
Here is an example of a week_field being set with optional minimum and maximum week constraints:
<%= f.week_field :week,
  min: Time.zone.today.beginning_of_year,
  max: Time.zone.today.end_of_year %>

Register your own flash types - Rails 4

In Rails 3, the ability to set flash parameters :notice and :alert in a controllerredirect_to call was added. Along with this change,ActionController::Base#notice andActionController::Base#alert were added as convenience accessors, which mapped to flash[:notice] and flash[:alert] respectively.
To set a custom flash type in your controller, you would have add the key/value pair to the controller flash hash, or you could also pass a hash to the optional :flashoption in redirect_to.
As of Rails 4, developers will have the ability to register their own flash types by using the new ActionController::Flash.add_flash_types macro style method.

The Rails 3 Way

Here is an example of setting a custom error flash type in Rails 3:
# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    ...
    flash[:error] = "An error message for the user"
    redirect_to home_path
  end
end

# app/views/home/index
<%= flash[:error] %>

The Rails 4 Way

Here is the same example as above, using Rails 4:
# app/controllers/application_controller.rb
class ApplicationController
    ...
  add_flash_types :error, :another_custom_type
end

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    ...
    redirect_to home_path,
      error: "An error message for the user"
  end
end

# app/views/home/index
<%= error %>

Saturday, January 4, 2014

Routing Concerns - Rails 4

The Rails config/routes.rb file encapsulates all the mappings from URLs to controller actions. Over the years, helpful additions have been added to slim this file down so that as developers, we can stop repeating ourselves. One example of this was the routing method resources, which maps four named routes to seven controller actions based on the HTTP request method.
As of Rails 4, routing concerns have been added to the router. Routing concerns allows you to declare common routes, which can be mixed into other resources and routes.

Example

A common example of duplication in the config/routes.rb file happens when a polymorphic association is nested under a parent resource.

Thursday, October 17, 2013

New features in Rails 4

Introduction:
Finally, the most awaited Rails 4.0 version has been released by the Rails team on 25th of June. Rails 4 has got huge changes. There are tons of new features available, which can make your life as a Rails developer a lot easier.  We will talk about the most exciting features in Rails 4 and why you should upgrade from Rails 3 version as soon as possible.
New features of Rails4
 1.  Ruby Versions
It is essential to note that Rails 4 would require Ruby 1.9.3 or higher, in fact Ruby 2.0.0 is recommended for your Rails 4 apps.