Showing posts with the label rails db

some minor things in rails

For Date format  .utc.strftime('%d-%m-%Y %H:%M:%S') Alternative to html_safe (raw("<strong class='text-danger'>Decline</strong")). select tag for form_for  <%=, options_for_select({|x|}, f.object.payment_currency), {include_blank: "Select Currency"}, { :class => 'form-control', required: true }) %> zip -r folder_name

Write simple html text in into rails tags

You can write simple text inside rails tag like link_to button_tag, submit_tag, text_field_tag etc.. (raw("<strong class='text-danger'>Decline</strong")) example : <%= link_to  (raw("<strong class='text-danger'>Decline</strong")), welcome_path %>

ActiveRecord::Base.connection.execute, robust record execute in rails

ActiveRecord::Base.transaction do          ActiveRecord::Base.connection.execute("UPDATE deposits SET amount = #{params[:adjust_amount].to_f} WHERE type = '#{@deposit.type}' AND id = #{} AND currency_id = '#{@deposit.currency_id}'").as_json if params[:adjust_amount].present?          ## update comment          if params[:mt5_history_id].present?            mt5_withdraw_history = Mt5History.find_by_id(params[:mt5_history_id])            mt5_withdraw_history.update(comment: params[:comment])          end        end This do loop will run until all parameter will execute if any record updatation is failed due to some reason all previous record update will be rollback!   

Download pdf by ajax or javascript or angular js

Click on button for generate pdf  $("#print_selected_label").on("click", function(){    data = []    $("input:checkbox.print_label:checked").each(function(){      data.push($(this).attr("id"));    });   //getting all information of checked checkbox    if(data.length > 0){    // if data is not null       In angular js controller         // var redirect_new = "/admin/v2/orders/print_multiple_label.pdf?" + jQuery.param(data);        // var pdf =, 'Map PDF', '');      By Creating a link by javascript       // var mydiv = document.getElementById("download_pdf");      // var aTag = document.createElement('a');      // var link = " admin/v2/orders/print_multiple_label.pdf?id="+data ;      // aTag.setAttribute('href',link);      // aTag.innerHTML = "link text";      // mydiv.appendChild(aTag);      //; By making http request    

Create worker in rails by sidekiq and redis

Add sidekiq to your Gemfile: Add this to your Gemfile gem 'sidekiq' Run bundle install bundle install Create worker rails g sidekiq:worker Test #will create app/workers/test_worker.rb class TestWorker   include Sidekiq::Worker   def perform(id, name)     # do something   end end Call worker without any time boundation TestWorker.perform_async(5, 'rahul') //use this anywhere from your rails app(controller, model, helpers..) Call worker within particular time period TestWorker.perform_in(5.minutes, 5, 'rahul')  //use this anywhere from your rails app(controller, model, helpers..) Call worker after specific time interval once only TestWorker.perform_at(5.minutes.from_now, 5, 'rahul')  //use this anywhere from your rails app(controller, model, helpers..) Start sidekiq on development bundle exec sidekiq Start sidekiq on production bundle exec sidekiq -d //run this first if you get some error then use second one bundle exec si

An error occurred while installing nokogiri (1.8.4), and Bundler cannot continue.

An error occurred while installing nokogiri (1.8.4), and Bundler cannot continue. Try this first and then bundle install again   sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev

Show Escape or Enter and tab in column or row in Rails

Show Escape or Enter and tab in column or row in Rails @users.each do |user|      raw(user.address.gsub(/\n/, '<br>'))   end //assuming you have \n or enter in your record and if you have another Special character then replace that character wiht respective html tag

Custom order of Record | | Order as specified || order_as_specified

Custom order of Record | | Order as specified || order_as_specified Install gem gem 'order_as_specified' bundle install or gem install order_as_specified write this line at top of your model / /that model you have to fetch record in custom order extend OrderAsSpecified Now in your controller method ids=[1,3,5,6,7,4,2] // assuming you have 7 record with this id's & and you want records in this order then Model.where(id: ids).order_as_specified(id: ids) //this will give you record in custom order Here is Working Example def index    premia1 = []    premia2 = []{|pi| premia1 << pi.premium}{|p| premia2 << p if p.premium_instructions.blank?}    permia = premia2 + premia1.uniq //add both array    ids = permia.pluck(:id) //getting ids from array into an array //learn about pluck in other post    @collection = Premium.where(id: ids). order_as_specified (id: ids) end Here we

DmL command || Sql Tutorial -7

DML Command Insert Command Its used to insert the record into table example- Command for inserting single record insert into <table name> values(value1, value2...) Command for inserting multiple command at a time insert into <table name> values(&col1, &col2...., &coln); whenever you enter query like this it will ask you to like this - enter a value for column1- value1.. and then hit enter  - enter a value for column2- value2.. and then hit enter - enter a value for column3- value3.. and then hit enter Now it will show 1 row created  if you want to create more record use / and hit enter SQL> /   hit enter // it will Execute most recent query again //this will so again and so on... - enter a value for column1- value1..  and then hit enter  - enter a value for column2- value2..  and then hit enter - enter a value for column3- value3..  and then hit enter // if you will miss any value here that will be inserted as NULL value Update command Used to upda

DDL command || Sql Tutorial -6

DDL Command CREATE Command It is used to create any data base object like tables, views, indexes, sequences, synonyms , users, functions, procedures, triggers, packages and so on. HOW TO CREATE A TABLE?            syn: CREATE TABLE <table_name>             (              <colname1> DATATYPE (size),               <colname2> DATATYPE (size),                : : : :,                : : : :,             ); INSERT Command This command is used for inserting new records into the tables          Syntax:           INSERT INTO <table_name>[(col1, col2,...., col n)]           VALUES(val1, val2,.....,val n);                  NOTE:  i) If number of columns in the table and number of values inserting in to the table      are equal, then no need to specify column names while inserting records.            ii) Char, Varchar2 and date type values should be enclosed in Single Quotes.            iii) If Number of inserting values are less than the

Naming convention in SQL Sql Tutorial -4

Naming Convention in SQL Rules to follow before specifying names(Object names, Column Names and Variable Names). Each name should begins alphabet Valid character set is a-z,A-Z,0-9,@,$,# and _ (underscore) Ex:  Emp123   Emp_o11 Names are not case sensitive Already existed names are not allowed Pre defined keywords (ReservedWords) are not allowed as names. Blankspace within a name is not allowed Max length of any name is 32 chars

Export Import component in react

 Export Import component in react See installation and configuration in my other blog Now Create a file into a public folder or anywhere into Root directory inside your project folder Create to directory into root directory         mkdir public           mkdir src Create two new into public folder index.html index.js Create two new file into src folder main.js  item.js Copy and paste code into index.html <!DOCTYPE html> <html> <head> <title>React - demo</title> </head> <body> <div id="root"></div> <script src="index.js"></script> </body> </html> Now into item.js import React from 'react'; class Item extends React.Component{ render(){ return( <div> Hello Item </div> ); } } export default Item; // you must have to make component exportable Now into main.js import React from 'react&#

how to run rails console on other port

Open Console or Terminal When we do rails s  it will run by default on 3000 port number if you want to run on specific port then rails s -p <port-number> Hit local host on by remote address  Go to browser            And type in the url bar or search bar -            If your address is like this localhost:3000 Here 3000 is a port number if you are running localhost on another port then remote address will be<your current port number>

my input a=12, but how do I print this in 3 digits?

There are many ways to do this. I am using the simplest way to print two digit number in three digit number. import java . util . Scanner ; class Digit { public static void main ( String [] args ) { Scanner sc = new Scanner ( System . in ); System . out . println ( "please enter any two digit number:" ); int n = sc . nextInt (); int k = 0 ; if ( n > 9 && n < 100 ) { k = n * 10 ; } else { System . out . println ( "please enter any two digit number:" ); } System . out . println ( "you entered " + n + " and three digit output of this number is " + k ); } Read More

Open rails server console on Terminal/Command Prompt

Login to Server via SSH or PEM file ls cd <domain name> cd/current RAILS_ENV=production bundle exec rails c now you will be in server console