Friday 5 September 2014

HOW TO APPLY DIFFERENT LAYOUTS FOR SAME CONTROLLER

class Events::EventsController < AuthenticatedController
layout :user_layout
#for admin
def new
end
def show

end
#for classifieds layout
def classifieds

end
protected
def user_layout
if params[:layout]=="admin"
"admin"
else
"classifieds"
end
end

end

Here i am applaying admin layout to new and show, classfieds to classifieds..

Inorder to apply those two layouts we need to pass layout="admin" as a paramater, in the same way layout="classifieds" for classifieds layout..

Ex: <li><a href="/events/new?layout=admin"><i class="fa fa-angle-double-right"></i>Events</a></li>
end

Wednesday 3 September 2014

MONGOID SEARCH

1, add gem to your gemfile
gem 'mongoid_search'

2, bundle install
3, include below statements to ur model event.rb
include Mongoid::Search
search_in :title,:venue,:launch_date,:tags,:description,:event_type
3, create 2 routes one for post and one for get

routes.rb
get 'search/:q' => 'events_user#search_result'
post 'search' => 'events_user#search_query'

4,create below methods in your events_user controller
def search_query
if search_params[:q].empty?
redirect_to :back
else
redirect_to '/events/search/' + search_params[:q]
end
end
def search_result
@search_result = Events::Event.full_text_search(params[:q]).paginate(:page => params[:page], :per_page => 10)
@latest=Events::Event.desc(:created_at).limit(10)
@q = search_params[:q]
end
private
def search_params
params.permit(:q)
end
5, write related view code in u r search_result .html.erb

<% @search_result.each do |event| %>
<div class="details-innercontent">
<div class="media">
<%= link_to(image_tag("#{event.banner_image.url}",:class=>"img-responsive" ,:alt=>"banner"),events_details_path(:id=>event.id),:class=>"pull-left") %>
<div class="media-body">
<div class="top-content">
<%= link_to raw(event.title),events_details_path(:id=>event.id), :class=>"media-heading" %>
<p><%=h truncate(event.description, :length => 80) %></p>
<% @tags=event.tags.split(",") %>
<% for tag in 0...@tags.length %>
<%= link_to @tags[tag], "#", :class=>"drama" %>
<% end %>
</div>
<div class="bottom-content">
<span class="pull-left"><%= event.created_at.strftime("%d %b %y") %></span>

</div> </div> </div> </div> <% end %>

Enjoy...............:-)

Monday 1 September 2014

Find all records for a given month

Here I have month and year as params...these two are change based on select box value....

Here i need to find records with in month choosen from select box....

Rails Query:
year=params[:month_name].split(",")[0].to_i
month=params[:month_name].split(",")[1].to_i
date=DateTime.new(year,month)
@all_events=Events::Event.where(:created_at => date.beginning_of_month..date.end_of_month)

From console:(Better understanding)
2.1.1 :005 > date=DateTime.new(2013,02)
 => Fri, 01 Feb 2013 00:00:00 +0000
2.1.1 :006 > date.beginning_of_month..date.end_of_month
 => Fri, 01 Feb 2013 00:00:00 +0000..Thu, 28 Feb 2013 23:59:59 +0000


Wednesday 27 August 2014

What is the use :anchor in link_to rails

<li class=""><%= link_to "International Events",events_events_filter_path(:id=>1,:anchor => 'critic-review'), :data=>{:toggle=>"tab"}%>
HtmlL:
<a data-toggle="tab" href="/events/1#citic-review">International Events</a>
it mewns it will execute a method and pont to some div or some place with id="rcitic-review"

Monday 25 August 2014

Dealing With routes


Define post method:

post '/listing/:id(.:format)', to: 'events#listing', :as=>"filter"

run rake routes

it will generate like this............

 events_filter POST   /events/listing/:id(.:format)                events/events#listing

in ur view:

<li><%= link_to "Latest Events",events_filter_path(:id=>"latest"), method: :post %></li>

This will generate: http url as:

http://localhost:3000/events/listing/latest

In ur latest method of events controller u can access as id:

def latest
   id=params[:id]
end





Thursday 21 August 2014

HOW TO SAVE IMAGES USING Mongoid::Paperclip

Mongoid::Paperclip

The ‘mongoid-paperclip’ gem is specially used in rails application with mongodb database where as the ‘paperclip’ gem is use in rails application with other than mongodb database like mysql, postgreSQL etc.

Before start this tutorial make sure that the ‘mongoid’ gem is already installed in your application. Lets follow following steps:
1. Include the gem in your Gemfile
gem "mongoid-paperclip", :require => "mongoid_paperclip"
2. Install gem (run on command prompt):
bundle install
3. Create controller (say Image ):
rails g controller Images index new show
4. Create model (say Image):
rails g model Image
5. Add following code in app/models/image.rb
class Image
include Mongoid::Document
include Mongoid::Paperclip
has_mongoid_attached_file :image
validates_attachment_content_type :banner_image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
6. Add following code in images controller.
def new
@images=Image.new
end
6. Use following code to create form (in views/Images/new.html.erb)
<%= form_for(@images, :url => {:action => 'create'},     :html => {:multipart => true}) do |f| %>
<%= f.file_field :image %>
<%= f.submit "Upload" %>
<% end %>
7. Use following code to Upload image (in ‘create’ action of  controllers/image_controller.rb)
def create
@image = Image.new(images_params)
if @image.save
redirect_to :action => :show, :id => @image.id
end
end
8. Use following code to view uploaded image (in ‘show’ action of controllers/image_controller.rb)
@id = params[:id]
@image = Image.find(@id)
9. and add in (views/image/show.html.erb)
<%= image_tag @image.image.url %>
10. Start server and run on browser:
localhost:3000/images/new
11. your images will saved in /public/system/images/image..
If you want see path of image..
in your terminal..
rails c
Image.last.image.url(:default)
12. if you want to add styles to your image..like specific width...use below code in your model
has_mongoid_attached_file :banner_image, :styles => { :default => "598x246>"}
13.Help Ful links:
https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation


U are using same image with different sizes in same project u can define three styles as follows:

has_mongoid_attached_file :image, :styles => { :small=> '124x89',:medium=> '247x173',:large=> '598x299'}
Then u can access image as following way:
<%= image_tag @image.image.url(:large) %> #for large image
<%= image_tag @image.image.url(:small) %> #for small image
<%= image_tag @image.image.url(:medium) %> #for medium image

If u make any changes..need to apply total images in ur table just simpl run below command:
 rake paperclip:refresh CLASS=Events::Photo Happy Learning.......


Tuesday 5 August 2014

Date and Month in single select box rails...last six months and last one year...


in controller:

@date = Date.today
@months = []
(0..17).each do |m|
@months << [@date.prev_month(m).strftime("%b, %Y"), @date.prev_month(m)]
end

In ERB:

<%= select_tag "month_year", options_for_select(@months) %>


In Order to get next 6 months and next year months:

@date = Date.today
@months = []
(0..17).each do |m|
  @months << [@date.next_month(m).strftime("%b %Y"), @date.next_month(m)]
end

Thursday 31 July 2014

RAILS 3-BETA-NO SUCH FILE TO LOAD RAILS/CLI(LOAD ERROR)


RAILS 3-BETA-NO SUCH FILE TO LOAD RAILS/CLI(LOAD ERROR)
When trying to create a rails project you might encounter the following error:

/Users/jfischer/.rvm/gems/ruby-1.9.1-p378/gems/rails-3.0.0.beta3/bin/rails:1:in `require’: no such file to load — rails/cli (LoadError)
from /Users/jfischer/.rvm/gems/ruby-1.9.1-p378/gems/rails-3.0.0.beta3/bin/rails:1:in `<top (required)>’
from /Users/jfischer/.rvm/gems/ruby-1.9.1-p378/bin/rails:19:in `load’
from /Users/jfischer/.rvm/gems/ruby-1.9.1-p378/bin/rails:19:in `<main>’
The problem can be solved by uninstalling all prior rails and active* beta versions using the gem command:
gem uninstall railties actionpack actionmailer activemodel activeresource activerecord activesupport
Then reinstall rails:
gem install rails --prerelease --no-ri --no-rdoc

Tuesday 29 July 2014

How to set terminal preference for rvm

Run command as login shell

gnome-terminal:

For RVM to work properly, you have to set the 'Run command as login shell' checkbox on the Title and Command tab inside of gnome-terminal's Settings page. Like this:

click on Edit Menu on terminal---->click on Profile Preferences--->

check the check box of "Run Command as login shell"

Tuesday 22 July 2014

.bashrc file to give shortcut names to commands........in ubuntu

$vi ~/.bashrc

press -->i to insert text..

alt+/--->type word alias...>to search for alias word

then write below statement..

alias gs="git status"

Open terminal and type.."gs" ---it will work like a git status command........



HOW TO ERB FILES SYNTAX ERROR USING "rails-erb-lint" GEm


rails-erb-lint



Installations:

$ gem install rails-erb-lint

Usage:
 
$cd your-rails-app/app/views
$rails-erb-lint check

It will check syntax of all .html.erb files and displays all invalid files....

Customize rails-erb-lint to display line numbers of syntax error for invalid files...

$gem which rails-erb-lint
#It will display path of rails-erb-lint gem
/home/saritha/.rvm/gems/ruby-2.1.1/gems/rails-erb-lint-1.0.8/lib/rails-erb-lint.rb

then, Open rails-erb-lint.rb in editor...

replace your module with below code......

rails-erb-lint.rb

module RailsErbCheck
  def self.valid_syntax?(erb)
    begin
      ActionView::Template::Handlers::Erubis.new(erb).result
    rescue SyntaxError => error
      puts "Error Occured In Line:#{error.inspect.split('syntax error')[0]}"
      return false
    rescue Exception
      return true
    end
  end
end

Now check your views...

$rails-erb-lint check

# Displays invalid files and line numbers as shown below:
Error Occured In Line:#<SyntaxError: (erubis:27: 
/home/saritha/ror/movierainbow/app/views/social/profiles/addfriends.html.erb => invalid
Error Occured In Line:#<SyntaxError: (erubis:9: 
/home/saritha/ror/movierainbow/app/views/social/profiles/friends.html.erb => invalid
"95 files, 2 invalid files"
saritha@sartitha-pc:~/ror/movierainbow/app/views$ rails-erb-lint check
Checking for files in current directory: /home/saritha/ror/movierainbow/app/views
"95 files, 0 invalid files"



Thank You.................Happy Rails Coding...........:-)







Monday 21 July 2014

REDIRECT_URI MISMATCH ERROR WITH GOOGLE OMNIAUTH

REDIRECT_URI MISMATCH

FIRST THING NEED TO CHECK REDIRECT URL OF YOUR APPLICATION...

IF THEY ARE SAME THEN YOU NEED TO GO WITH SECOND OPTION,

EX: OmniAuth.config.full_host = "[HOST NAME]"
OmniAuth.config.full_host = "http://dev.mr.wedev.in"
#IT IS FOR YOUR GLOBAL APPLICATION

to override call back url......

OmniAuth.config.full_host = 'http://localhost:3000'
#IT IS FOR YOUR LOCAL APPLICATION

OmniAuth.config.full_host  no need to use in local system...but it is mainly used in production enviroment...it initializes redirect url....

customize Page_entries_info in WILL PAGINATE RAILS 4


Create One Hellper in config/initializers/will_paginate.rb

Paste below code in your hellper i.e, will_paginate.rb


WillPaginate::ViewHelpers.pagination_options[:previous_label] = 'Previous page'
require 'will_paginate/core_ext'

module WillPaginate
  # = Will Paginate view helpers
  #
  # The main view helper, #will_paginate, renders
  # pagination links for the given collection. The helper itself is lightweight
  # and serves only as a wrapper around LinkRenderer instantiation; the
  # renderer then does all the hard work of generating the HTML.
  #
  # == Global options for helpers
  #
  # Options for pagination helpers are optional and get their default values from the
  # <tt>WillPaginate::ViewHelpers.pagination_options</tt> hash. You can write to this hash to
  # override default options on the global level:
  #
  #   WillPaginate::ViewHelpers.pagination_options[:previous_label] = 'Previous page'
  #
  # By putting this into "config/initializers/will_paginate.rb" (or simply environment.rb in
  # older versions of Rails) you can easily translate link texts to previous
  # and next pages, as well as override some other defaults to your liking.
  module ViewHelpers
    # default options that can be overridden on the global level
    @@pagination_options = {
      :class          => 'pagination',
      :previous_label => 'Previous',
      :next_label     => 'Next',
      :inner_window   => 4, # links around the current page
      :outer_window   => 1, # links around beginning and end
      :separator      => ' ', # single space is friendly to spiders and non-graphic browsers
      :param_name     => :page,
      :params         => nil,
      :renderer       => 'WillPaginate::LinkRenderer',
      :page_links     => true,
      :container      => true
    }
    mattr_reader :pagination_options

    # Renders Digg/Flickr-style pagination for a WillPaginate::Collection
    # object. Nil is returned if there is only one page in total; no point in
    # rendering the pagination in that case...
    #
    # ==== Options
    # Display options:
    # * <tt>:previous_label</tt> -- default: "« Previous" (this parameter is called <tt>:prev_label</tt> in versions <b>2.3.2</b> and older!)
    # * <tt>:next_label</tt> -- default: "Next »"
    # * <tt>:page_links</tt> -- when false, only previous/next links are rendered (default: true)
    # * <tt>:inner_window</tt> -- how many links are shown around the current page (default: 4)
    # * <tt>:outer_window</tt> -- how many links are around the first and the last page (default: 1)
    # * <tt>:separator</tt> -- string separator for page HTML elements (default: single space)
    #
    # HTML options:
    # * <tt>:class</tt> -- CSS class name for the generated DIV (default: "pagination")
    # * <tt>:container</tt> -- toggles rendering of the DIV container for pagination links, set to
    #   false only when you are rendering your own pagination markup (default: true)
    # * <tt>:id</tt> -- HTML ID for the container (default: nil). Pass +true+ to have the ID
    #   automatically generated from the class name of objects in collection: for example, paginating
    #   ArticleComment models would yield an ID of "article_comments_pagination".
    #
    # Advanced options:
    # * <tt>:param_name</tt> -- parameter name for page number in URLs (default: <tt>:page</tt>)
    # * <tt>:params</tt> -- additional parameters when generating pagination links
    #   (eg. <tt>:controller => "foo", :action => nil</tt>)
    # * <tt>:renderer</tt> -- class name, class or instance of a link renderer (default:
    #   <tt>WillPaginate::LinkRenderer</tt>)
    #
    # All options not recognized by will_paginate will become HTML attributes on the container
    # element for pagination links (the DIV). For example:
    #
    #   <%= will_paginate @posts, :style => 'font-size: small' %>
    #
    # ... will result in:
    #
    #   <div class="pagination" style="font-size: small"> ... </div>
    #
    # ==== Using the helper without arguments
    # If the helper is called without passing in the collection object, it will
    # try to read from the instance variable inferred by the controller name.
    # For example, calling +will_paginate+ while the current controller is
    # PostsController will result in trying to read from the <tt>@posts</tt>
    # variable. Example:
    #
    #   <%= will_paginate :id => true %>
    #
    # ... will result in <tt>@post</tt> collection getting paginated:
    #
    #   <div class="pagination" id="posts_pagination"> ... </div>
    #
    # def will_paginate(collection = nil, options = {})
    #   options, collection = collection, nil if collection.is_a? Hash
    #   unless collection or !controller
    #     collection_name = "@#{controller.controller_name}"
    #     collection = instance_variable_get(collection_name)
    #     raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " +
    #       "forget to pass the collection object for will_paginate?" unless collection
    #   end
    #   # early exit if there is nothing to render
    #   return nil unless WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1

    #   options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options
    #   if options[:prev_label]
    #     WillPaginate::Deprecation::warn(":prev_label view parameter is now :previous_label; the old name has been deprecated", caller)
    #     options[:previous_label] = options.delete(:prev_label)
    #   end

    #   # get the renderer instance
    #   renderer = case options[:renderer]
    #   when String
    #     options[:renderer].to_s.constantize.new
    #   when Class
    #     options[:renderer].new
    #   else
    #     options[:renderer]
    #   end
    #   # render HTML for pagination
    #   renderer.prepare collection, options, self
    #   renderer.to_html
    # end

    # Wrapper for rendering pagination links at both top and bottom of a block
    # of content.
    #
    #   <% paginated_section @posts do %>
    #     <ol id="posts">
    #       <% for post in @posts %>
    #         <li> ... </li>
    #       <% end %>
    #     </ol>
    #   <% end %>
    #
    # will result in:
    #
    #   <div class="pagination"> ... </div>
    #   <ol id="posts">
    #     ...
    #   </ol>
    #   <div class="pagination"> ... </div>
    #
    # Arguments are passed to a <tt>will_paginate</tt> call, so the same options
    # apply. Don't use the <tt>:id</tt> option; otherwise you'll finish with two
    # blocks of pagination links sharing the same ID (which is invalid HTML).
    def paginated_section(*args, &block)
      pagination = will_paginate(*args).to_s

      unless ActionView::Base.respond_to? :erb_variable
        concat pagination
        yield
        concat pagination
      else
        content = pagination + capture(&block) + pagination
        concat(content, block.binding)
      end
    end

    # Renders a helpful message with numbers of displayed vs. total entries.
    # You can use this as a blueprint for your own, similar helpers.
    #
    #   <%= page_entries_info @posts %>
    #   #-> Displaying posts 6 - 10 of 26 in total
    #
    # By default, the message will use the humanized class name of objects
    # in collection: for instance, "project types" for ProjectType models.
    # Override this with the <tt>:entry_name</tt> parameter:
    #
    #   <%= page_entries_info @posts, :entry_name => 'item' %>
    #   #-> Displaying items 6 - 10 of 26 in total
    def page_entries_info(collection, options = {})
      entry_name = options[:entry_name] ||
        (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' '))

      if collection.total_pages < 2
        case collection.size
        when 0; "No #{entry_name.pluralize} found"
        when 1; "Displaying <b>1</b> #{entry_name}"
        else;   "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}"
        end
      else
        %{SHOWING  %d-%d of %d} % [
          collection.offset + 1,
          collection.offset + collection.length,
          collection.total_entries
        ]
      end
    end

    if respond_to? :safe_helper
      safe_helper :will_paginate, :paginated_section, :page_entries_info
    end

    def self.total_pages_for_collection(collection) #:nodoc:
      if collection.respond_to?('page_count') and !collection.respond_to?('total_pages')
        WillPaginate::Deprecation.warn %{
          You are using a paginated collection of class #{collection.class.name}
          which conforms to the old API of WillPaginate::Collection by using
          `page_count`, while the current method name is `total_pages`. Please
          upgrade yours or 3rd-party code that provides the paginated collection}, caller
        class << collection
          def total_pages; page_count; end
        end
      end
      collection.total_pages
    end
  end

  # This class does the heavy lifting of actually building the pagination
  # links. It is used by the <tt>will_paginate</tt> helper internally.
  class LinkRenderer

    # The gap in page links is represented by:
    #
    #   <span class="gap">&hellip;</span>
    attr_accessor :gap_marker

    def initialize
      @gap_marker = '<span class="gap">&hellip;</span>'
    end

    # * +collection+ is a WillPaginate::Collection instance or any other object
    #   that conforms to that API
    # * +options+ are forwarded from +will_paginate+ view helper
    # * +template+ is the reference to the template being rendered
    def prepare(collection, options, template)
      @collection = collection
      @options    = options
      @template   = template

      # reset values in case we're re-using this instance
      @total_pages = @param_name = @url_string = nil
    end

    # Process it! This method returns the complete HTML string which contains
    # pagination links. Feel free to subclass LinkRenderer and change this
    # method as you see fit.
    def to_html
      links = @options[:page_links] ? windowed_links : []
      # previous/next buttons
      links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:previous_label])
      links.push    page_link_or_span(@collection.next_page,     'disabled next_page', @options[:next_label])

      html = links.join(@options[:separator])
      html = html.html_safe if html.respond_to? :html_safe
      @options[:container] ? @template.content_tag(:div, html, html_attributes) : html
    end

    # Returns the subset of +options+ this instance was initialized with that
    # represent HTML attributes for the container element of pagination links.
    def html_attributes
      return @html_attributes if @html_attributes
      @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class])
      # pagination of Post models will have the ID of "posts_pagination"
      if @options[:container] and @options[:id] === true
        @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination'
      end
      @html_attributes
    end

  protected

    # Collects link items for visible page numbers.
    def windowed_links
      prev = nil

      visible_page_numbers.inject [] do |links, n|
        # detect gaps:
        links << gap_marker if prev and n > prev + 1
        links << page_link_or_span(n, 'current')
        prev = n
        links
      end
    end

    # Calculates visible page numbers using the <tt>:inner_window</tt> and
    # <tt>:outer_window</tt> options.
    def visible_page_numbers
      inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i
      window_from = current_page - inner_window
      window_to = current_page + inner_window

      # adjust lower or upper limit if other is out of bounds
      if window_to > total_pages
        window_from -= window_to - total_pages
        window_to = total_pages
      end
      if window_from < 1
        window_to += 1 - window_from
        window_from = 1
        window_to = total_pages if window_to > total_pages
      end

      visible   = (1..total_pages).to_a
      left_gap  = (2 + outer_window)...window_from
      right_gap = (window_to + 1)...(total_pages - outer_window)
      visible  -= left_gap.to_a  if left_gap.last - left_gap.first > 1
      visible  -= right_gap.to_a if right_gap.last - right_gap.first > 1

      visible
    end

    def page_link_or_span(page, span_class, text = nil)
      text ||= page.to_s
      text = text.html_safe if text.respond_to? :html_safe

      if page and page != current_page
        classnames = span_class && span_class.index(' ') && span_class.split(' ', 2).last
        page_link page, text, :rel => rel_value(page), :class => classnames
      else
        page_span page, text, :class => span_class
      end
    end

    def page_link(page, text, attributes = {})
      @template.link_to text, url_for(page), attributes
    end

    def page_span(page, text, attributes = {})
      @template.content_tag :span, text, attributes
    end

    # Returns URL params for +page_link_or_span+, taking the current GET params
    # and <tt>:params</tt> option into account.
    def url_for(page)
      page_one = page == 1
      unless @url_string and !page_one
        @url_params = {}
        # page links should preserve GET parameters
        stringified_merge @url_params, @template.params if @template.request.get?
        stringified_merge @url_params, @options[:params] if @options[:params]

        if complex = param_name.index(/[^\w-]/)
          page_param = parse_query_parameters("#{param_name}=#{page}")

          stringified_merge @url_params, page_param
        else
          @url_params[param_name] = page_one ? 1 : 2
        end

        url = @template.url_for(@url_params)
        return url if page_one

        if complex
          @url_string = url.sub(%r!((?:\?|&amp;)#{CGI.escape param_name}=)#{page}!, "\\1\0")
          return url
        else
          @url_string = url
          @url_params[param_name] = 3
          @template.url_for(@url_params).split(//).each_with_index do |char, i|
            if char == '3' and url[i, 1] == '2'
              @url_string[i] = "\0"
              break
            end
          end
        end
      end
      # finally!
      @url_string.sub "\0", page.to_s
    end

  private

    def rel_value(page)
      case page
      when @collection.previous_page; 'prev' + (page == 1 ? ' start' : '')
      when @collection.next_page; 'next'
      when 1; 'start'
      end
    end

    def current_page
      @collection.current_page
    end

    def total_pages
      @total_pages ||= WillPaginate::ViewHelpers.total_pages_for_collection(@collection)
    end

    def param_name
      @param_name ||= @options[:param_name].to_s
    end

    # Recursively merge into target hash by using stringified keys from the other one
    def stringified_merge(target, other)
      other.each do |key, value|
        key = key.to_s # this line is what it's all about!
        existing = target[key]

        if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?)
          stringified_merge(existing || (target[key] = {}), value)
        else
          target[key] = value
        end
      end
    end

    def parse_query_parameters(params)
      if defined? Rack::Utils
        # For Rails > 2.3
        Rack::Utils.parse_nested_query(params)
      elsif defined?(ActionController::AbstractRequest)
        ActionController::AbstractRequest.parse_query_parameters(params)
      elsif defined?(ActionController::UrlEncodedPairParser)
        # For Rails > 2.2
        ActionController::UrlEncodedPairParser.parse_query_parameters(params)
      elsif defined?(CGIMethods)
        CGIMethods.parse_query_parameters(params)
      else
        raise "unsupported ActionPack version"
      end
    end
  end
end

then change page_entries_info method...
according to your requirements.....

Wednesday 16 July 2014

link_to, image_tag raw combination......

link_to +image_tag +raw 

<%= link_to(raw(image_tag("/assets/add-group-icon.png")+raw('<span>Compose a Message</span>')),"#",:class=>"create-group") %>

Thursday 10 July 2014

ADD CUSTOM FIELDS TO DEVISE GEM

To add Custom fileds to devise gem:

$ rails generate devise:views
#to generate views

$rails generate migration AddLocationColumnToUsers location_name:string gender:string

#Add field names to users table with migration

then,

Add fields to signup form....

then add below lines to your application controller...

#strong parameters saving in database
before_filter :configure_permitted_parameters, if: :devise_controller?

 protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:location_name,:gender,:email, :password, :password_confirmation) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:location_name,:gender,:email, :password, :password_confirmation) }
  end

:-)

Monday 7 July 2014

DATA ATTRIBUTE-IN RAILS4--(Rails - link_to helper with data-* attribute [duplicate])


DATA ATTRIBUTE IN RAILS4:


<%= link_to("Post Your Free AD Now!", "/classifieds/select-catagory", class: "btn btn-primary", "data-toggle" => 'modal', 'data-target' => '#myModal', 'data-redirect-after-login' => "/" ) %>

Thursday 3 July 2014

Google Plus Integration

Google Plus Integration:

Step1: you need to create an app in google to get “Client Id” and “Client Secret Id”
https://code.google.com/apis/console/

  1. Clck on Project Menu
  2. Fill project name and Project Id
  3. Enable an API (I.E, GOOGLE + API), Turn off remaining all API's
  4. click on Credentails column.
  5. Click on New Client Id.(select web application,set redirect url )(EX: Redirect url:http://localhost:3000/users/auth/google_oauth2/callback)
  6. Then you will get Clent Id and Client Secret Id

Step 2: Add the gems in your gem file
gem 'devise'
gem 'omniauth'

gem 'omniauth-google-oauth2' 
then, Run bundle.

Step3:You need two more columns to store provider type and userid given from google
rails g migration AddProviderToUsers provider:string uid:string
Runt rake db:migrate to insert the columns in users table.
Step4:Go the user model “user.rb” and add the following line
devise :omniauthable, :database_authenticatable, :registerable,

         :recoverable, :rememberable, :trackable, :validatable

Step 5:Now you need to declare the provider name and client id and key.Go to the file config/initializers/devise.rb and the following line
require 'omniauth-google-oauth2'

config.omniauth :google_oauth2, "[ClentId]", "[Client Secret Id]", { access_type: "offline", approval_prompt: "" }

Step 6: Add below 2 line to your layout
<%= link_to "Sign out", destroy_user_session_path,:method => :delete %>

<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>

Step 7:Before creating the call back method change your route like below
 devise_for :users, path_names: {sign_in: "login", sign_out: "logout"},

                   controllers: {omniauth_callbacks: "omniauth_callbacks"}
Step 8:Create a new controller named as omniauth_callbacks_controller.rb.Add the following method in it.
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def all
    user = User.from_omniauth(request.env["omniauth.auth"])
    if user.persisted?
      flash.notice = "Signed in!"
      sign_in_and_redirect user
    else
      session["devise.user_attributes"] = user.attributes
      redirect_to new_user_registration_url
    end
  end
  alias_method :google_oauth2, :all

end
Step 9:Add the following block in your user model.
def self.from_omniauth(auth)
  where(auth.slice(:provider, :uid)).first_or_create do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.username = auth.info.nickname
    user.email = auth.info.email
  end
end
def password_required?
  super && provider.blank?
end
def update_with_password(params, *options)
  if encrypted_password.blank?
    update_attributes(params, *options)
  else
    super
  end

end

Happy Rails Coding...............

Sorce from:https://github.com/zquestz/omniauth-google-oauth2/issues/20

Tuesday 24 June 2014

MONGO DB BASICS FOR BEGINNERS


Mapping RDBMS TO MongoDB:

RDBMSMongoDB
DatabaseDatabase
TableCollection
Tuple/RowDocument
columnField
Table JoinEmbedded Documents
Primary KeyPrimary Key (Default key _id provided by mongodb itself)
Database Server and Client
Mysqld/Oraclemongod
mysql/sqlplusmongo

Basic Queries:

Use database:
>use [database_name] #create and switch to that database
Ex: >use mongo
#switch to mongo database

show collections:
>show collections #To show collections in mongo database.

Current Database:
>db #To show current database

To show Databases:
>show dbs #To show all databases
Note: Its not displaying sari database because there is no data in sari database. first insert some records in database.

Drop Database:
>db.dropdatabase()#To drop a current database

Select Records:
>db.collectionName.findOne()
#To show first record in a collection
>db.collectionName.find().pretty
#To show all fields in a format
>db.collectionName.find().limit(5)
>db.collectionName.find( { _id: 5 } )
#displays records with id=5
>db.collection.find( { field: { $gt: value1, $lt: value2 } } );
Ex:>db.students.find( { score: { $gt: 0, $lt: 2 } } )
#To specify ranges
Create a Collection:
>db.createCollection(nameoptions)
#To create a collection
Ex: db.createCollection(student, {name: <string>, qual: <string>, age: <number>})

Insert Values Into Collection:

>db.collectionname.insert( { field1: value1, field2: val2} )
Ex:db.students.insert( { name: "ss", qual: "btech", age: 15 } )

To Remove Specific Documents:
>db.collection.remove()
#to delete a document in collection
Ex:>db.students.remove( { age: { $gt: 20 } } )