Saturday, 7 October 2017

Nested form

Question to answer


1. Gem file: 
          gem "nested_form"

 application.js:
         //= require jquery_nested_form


2. Question controller:
         params.require(:question).permit(:question_type, :body, answers_attributes: [:id, :question_id, :body, :_destroy])

3. Question.rb:
        has_many :answers, dependent: :destroy
        accepts_nested_attributes_for :answers, :allow_destroy => true

4. answer.rb:
       belongs_to :question

5. question form: 

     <table id="tasks">
    <%= form.fields_for :answers do |answer_form| %>
      <div class="row">
          <%= answer_form.text_area :body  ,class: "form-control mynewinput1", placeholder: "Question" %>
          <%= answer_form.link_to_remove "Remove", class: "btn btn-danger" %>
      </div>
    <% end %>
  </table>
<p><%= form.link_to_add "Add a Answer", :answers, :data => { :target => "#tasks" } %></p>

Thursday, 7 September 2017

Social login facebook,twitter ..

Gemfile:

gem "oauth"
gem "oauth2"
gem 'omniauth-oauth2'
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem 'omniauth-google-oauth2'
gem 'omniauth-linkedin'
gem 'omniauth-github'
gem 'omniauth-pinterest'

--------------------------------------------------

Model generate:

 rails g model authentication provider:string uid:string user_id:integer token:text token_expired_at:datetime

--------------------------------------------------

app/model/authentication.rb:

class Authentication < ApplicationRecord
belongs_to :user
def self.from_omniauth(auth)
    authenticate = where(provider: auth['provider'], :uid=>auth['uid']).first_or_initialize
    register_user = User.find_by(email: auth.info.email)
    if authenticate.user
      return authenticate.user
    elsif register_user
      register_user.authentications.create(provider: auth['provider'], :uid=>auth['uid'])
      return register_user
    else
      user = User.new(
        email: auth.info.try(:email),                      
        password: Devise.friendly_token.first(8)
      )
      if user.email.blank?
        user.email=auth.extra.raw_info.id.to_s+"@gmail.com"
      end
      user.save!(:validate => false)
      user.authentications.create(provider: auth['provider'], :uid=>auth['uid'],token: auth["credentials"]["token"])
      return user
   end
  end
end

-------------------------------------------

User.rb

before_create :confirmation_token
has_many :authentications, dependent: :destroy
validates :email, :uniqueness => {:allow_blank => true}

-------------------------------------------

config/intializers/omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, "#{ENV['FACEBOOK_APP_ID']}", "#{ENV['FACEBOOK_APP_SERCRET']}", :scope => 'email, user_friends, manage_pages, pages_show_list'
  provider :google_oauth2, "#{ENV['GOOGLE_APP_ID']}", "#{ENV['GOOGLE_APP_SERCRET']}", scope: 'userinfo.profile,youtube,email', provider_ignores_state: true, prompt: :consent
  provider :twitter, "#{ENV['Twitter_APP_ID']}", "#{ENV['Twitter_APP_SERCRET']}"
  provider :linkedin, "#{ENV['Linkedin_APP_ID']}", "#{ENV['Linkedin_APP_SERCRET']}"
  provider :github, "#{ENV['Github_APP_ID']}", "#{ENV['Github_APP_SERCRET']}", :scope => 'email'
  provider :pinterest, "#{ENV['Pinterest_APP_ID']}", "#{ENV['Pinterest_APP_SERCRET']}", :scope => 'read_public,write_public'
end

--------------------------------------------
application.yml:

default:
  DATABASE_ADAPTER: postgresql
  DATABASE_USER: root
  DATABASE_PASSWORD: root
  DATABASE_NAME: go_foot_ball
  DATABASE_HOST: localhost
  DOMAIN: localhost
  FACEBOOK_APP_ID: xxxxxxxxxx
  FACEBOOK_APP_SERCRET: xxxxxxxxxxxxxxxxxxx
  TWITTER_CONSUMER_KEY: xxxxxxxxxxxxxxxxx
  TWITTER_CONSUMER_SECRET: xxxxxxxxxxxxxxxxx
  INSTAGRAM_APP_ID: xxxxxxxxxxxxxxxxxxxxxxxxx
  INSTAGRAM_APP_SERCRET: xxxxxxxxxxxx
  # AWS_ACCESS_KEY_ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  # AWS_SECRET_ACCESS_KEY:xxxxxxxxxxxxxxxxxxxxxxxxxx
  # REGION: 'us-west-2'
  # AWS_BUCKET_NAME: xxxxxxxxxxxx
  # FACEBOOK_APP_VERSION: 'v2.8'

development:
  DATABASE_ADAPTER: postgresql
  DATABASE_USER: root
  DATABASE_PASSWORD: root
  DATABASE_NAME: go_foot_ball
  DATABASE_HOST: localhost
  DOMAIN: localhost
  FACEBOOK_APP_ID: xxxxxxxxxxxx
  FACEBOOK_APP_SERCRET: xxxxxxxxxxxxxxxxx
  TWITTER_CONSUMER_KEY: xxxxxxxxxxxxxxxxxx
  TWITTER_CONSUMER_SECRET: xxxxxxxxxxxxxxxxxx
  INSTAGRAM_APP_ID: xxxxxxxxxxxxxxxxxxxxxxxx
  INSTAGRAM_APP_SERCRET: xxxxxxxxxxxxxxxxxxxxxx

testing:
  DATABASE_ADAPTER: postgresql
  DATABASE_USER: root
  DATABASE_PASSWORD: root
  DATABASE_NAME: go_foot_ball
  DATABASE_HOST: localhost
  DOMAIN: localhost

production:
  DATABASE_ADAPTER: postgresql
  DATABASE_USER: root
  DATABASE_PASSWORD: root
  DATABASE_NAME: go_foot_ball
  DATABASE_HOST: localhost
  DOMAIN: localhost

----------------------------------------------

routes:

  match '/auth/:provider/callback', :to => 'pages#create', via: [:get, :post]
  match '/auth/failure', :to => 'pages#failure', via: [:get, :post]

---------------------------------------------

app/controller/pages_controller.rb:

def create
    user = Authentication.from_omniauth(request.env["omniauth.auth"])
    if user
      flash[:notice] = "Authentication successful."
     sign_in :user, user
     redirect_to root_path
    else
        flash[:notice] = "Authentication Failed."
        redirect_to "/users/sign_up"
    end
  end
  def failure
  end
  

Friday, 1 September 2017

How To: Add :confirmable to Users

Modifying the User Model

First, add devise :confirmable to your models/user.rb file

devise :registerable, :confirmable

Create a New Migration

Then, do the migration as:

rails g migration add_confirmable_to_devise

Will generate db/migrate/YYYYMMDDxxx_add_confirmable_to_devise.rb. Add the following to it in order to do the migration.

class AddConfirmableToDevise < ActiveRecord::Migration
  # Note: You can't use change, as User.update_all will fail in the down migration
  def up
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime
    # add_column :users, :unconfirmed_email, :string # Only if using reconfirmable
    add_index :users, :confirmation_token, unique: true
    User.all.update_all confirmed_at: DateTime.now
  end

  def down
    remove_columns :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
  end
end
You can also generate the corresponding Devise views if they have not yet been created:

rails generate devise:views users
Do the migration rake db:migrate

Restart the server.

If you are not using :reconfirmable (i.e leave the commented out lines as they are in the change method described above), update the configuration in config/initializers/devise.rb

config.reconfirmable = false

SMTP Setting:

config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => "587",
    :domain => "localhost",
    :user_name => "zz.zz@gmail.com",
    :password => "zzzzzzzzzz",
    :authentication => "plain",
    :enable_starttls_auto => true
  } 

Tuesday, 18 July 2017

How to add Admin panel in rails application

Add column:

rails g migration AddRoleToUsers role:string is_admin:boolean is_active:boolean

role, default: "member"

1. application controller with user over
 
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :user_admin, expect:[:after_sign_in_path_for]
  include ApplicationHelper
  layout :set_layout
  before_action :configure_permitted_parameters, if: :devise_controller?
  # before_action :check_subscription
  def after_sign_in_path_for(resource)
    resource.is_admin? ? admin_root_path : root_path
  end

def user_admin
    if request.fullpath.split("/")[1] == "admin"
      if current_user.role != 'admin'
        redirect_to root_path
      else
        request.url
      end
    else
    end
  end

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:email, :password, :password_confirmation, :role, :first_name, :last_name, :image, :is_active, :is_admin])
    devise_parameter_sanitizer.permit(:account_update, keys: [:email, :password, :password_confirmation, :role, :first_name, :last_name, :image, :is_active, :is_admin])

  end

def authentication_admin!
      unless current_user.is_admin?
        flash[:alert] = "You are not authorized to perform this action."
        redirect_to(request.referrer || root_path)
      end
  end

end


2. admin_controller

class AdminController < ApplicationController
  layout 'admin'
  before_action :authentication_admin!

  def index
  end
end

3. ApplicationHelper
 
module ApplicationHelper

def is_namespace_admin
begin
return false if !(request.base_url && request.url)
request.url.split(request.base_url)[1].split("/")[1] == "admin"
rescue => error
return false
end
end
  def is_not_namespace_admin
    !is_namespace_admin
  end
  def set_layout
  is_namespace_admin ? "admin" : "application"
  end

end

4. routes

 namespace :admin, module: nil  do
    root "admin#index"
    resources :users
  end

5. layout
6. config/initializers/assets.rb

  Rails.application.config.assets.precompile += %w( admin.css admin.js )

7.User.rb

def is_admin?
  return true if self.role =="admin"
  end

----------------------------------------------------


Friday, 30 June 2017

Heroku Pg backup

1. git remote add heroku heroku URL
2.  heroku pg:backups capture
3. pg_restore --verbose --clean --no-acl --no-owner -h localhost -U Username -d Databasename latest.dump

Tuesday, 27 June 2017

Flash messages

views/layouts/application.html.erb:-

<div class="FlashNotice">
  <% flash.each do |key, value| %>
    <div class="<%= flash_class(key) %> fade in">
      <a href="#" data-dismiss="alert" class="close">×</a>
      <%= value %>
    </div>
  <% end %>
</div>

<style>
.FlashNotice .alert{
margin-bottom: 0px;
}
</style>


application_helper.rb:-

def flash_class(level)
    case level
    when 'notice' then "alert alert-info"
    when 'success' then "alert alert-success"
    when 'error' then "alert alert-error"
    when 'alert' then "alert alert-error"
    end
  end

application.js:-

setTimeout(function() {
    $('.FlashNotice').fadeOut('fast');
}, 5000);





Wednesday, 7 June 2017

Active Admin CKediter

Add it to your Gemfile
gem 'activeadmin_ckeditor'
--------------------------------------------------------------------
Follow the instructions for galetahub/ckeditor (gem, mount in routes and rails generate for your file uploads if wanted), then add the following to /config/initializers/active_admin.rb
# To load a javascript file:
config.register_javascript 'ckeditor/init.js'
-----------------------------------------------------------------
In your resource you'll need to add to your form:
form do |f|
  f.inputs do
    f.input :foo
    f.input :bar, :as => :ckeditor
  end
  f.actions
end
--------------------------------------------------------------
I've also found it necessary to add to app/assets/stylesheets/active_admin.css.scss to fit it to on the form:
.cke_chrome {
  width: 79.5% !important;
  overflow: hidden;
}
-------------------------------------------------------------
index do
    selectable_column
    id_column
    column :descrption.html_safe
    column :body.html_safe
end
----------------------------------------------------------------
URL: https://github.com/activeadmin/activeadmin/wiki/Ckeditor-integration