Useful tips for Rails Beginner

At initial stage of rails learning when you are trying your hands on different gems and commands, If you strictly follow any tutorial and if it is still not giving result then restart rails server. It has solved most of my such issues.


If you do not mention version in gem file then it will automatically take the supported one.
Like Use
gem ‘rspec’
Instead of
gem ‘rspec’, ‘~> 3.4’


If you want to display variable then below are various ways:
1) Use puts and It will display that in console window where rail server is running.
puts “Need to debug this line”
@articles.each do |one|
putsone.title
end

2) Use render and it will halt the execution and display values directly in browser.
render json: @articles

3) Try “pry” gem for debugging console. install “pry” gem and add below line to halt the execution in controller file. It will then open pry console where you can entry variable name like >@articles and hit enter to view result.
binding.pry


scaffolding is great in Rail. Below line will generate all the CRUD pages without making any single line of code.
$rails generate scaffold Article title:string body:text

This is known as “Metaprogramming” – writing a program which outputs another program.


 

Advertisements

Adding a custom field in Devise in Rails 4+

Assuming that you have already installed devise gem https://github.com/plataformatec/devise in your rails project, below are the steps to create User module.

config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

$rails generate devise:install
$rails generate devise User

Before doing “rake db:migrate”, you can change fields in the migrate file and then can migrate db to change the schema.

Run below command to add extra fields in the User model, followed by “rake db:migrate”
$rails generate migration add_columns_to_users admin:boolean firstname:string lastname:string

Adding new fields in the templates are easy, you just need to copy paste the existing field format and follow the guideline. You can immediately see the new fields in the browser but if you will save those field, It will not be saved in database.

“$rails console” use this command to open rails terminal and add below code to check the current database records.
> User.last => shows last user

This is because the way Rails 4 deals with “mass assignment”. You can create new controlller file and add below code and it will handle that.

class RegistrationsController < Devise::RegistrationsController

private

def sign_up_params
params.require(:user).permit(:firstname, :lastname, :username, :email, :password, :password_confirmation)
end

def account_update_params
params.require(:user).permit(:firstname, :lastname, :username, :email, :password, :password_confirmation, :current_password)
end
end

Bootstrap error on Rails – ExecJS :: ProgramError

I have followed https://github.com/twbs/bootstrap-rubygem and followed all below steps to install bootstrap 4 on Rails 5.

Added below code in Gemfile:
gem 'bootstrap', '~> 4.0.0'
gem 'jquery-rails', '~> 4.3.1'

Replace below code in application.scss (Renamed from .css to .scss)
@import "bootstrap";

Added below 3 lines in applcation.js
//= require jquery3
//= require popper
//= require bootstrap-sprockets

$bundle install => Install gems
$rails server => Restart server

After following all steps, I was getting below error
ExecJS::ProgramError

Pointing to
application.html.erb => <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

I have removed below code from Gem file and It has solved this issue.
gem 'duktape'

Solution for sqlite3.rb:6:in `require’: 126: The specified module could not be found

While learning ROR, I was facing some issues with sqlite.

I have first installed Ruby and Rails from the online links. All tutorials said, if you installed Rails through Rails Installer, you already have SQLite installed. But when I tried below command, It didn’t recognized sqlite3 even after changing environment variables.

$ sqlite3 --version
$ 'sqlite3' is not recognized as an internal or external command,
operable program or batch file.

I had installed SqLite separately from https://www.sqlite.org/index.html and added .dll files under specific folder and added in environment environment variables. Still I was receiving error.

Then executed below command and added bove downloaded .dll files under D:\Ruby25-x64\bin and It worked.
>gem install sqlite3 --platform=ruby -- --with-sqlite3-dir=D:/system/sqlite3 --with-sqlite3-include=D:/system/sqlite3

Now below command has successfully launched first Rail webpage on http://localhost:3000/

$ rails new blog
$ cd blog
$ ruby bin\rails server

Convert JSON string to number

When you are getting API response as a JSON and all numeric fields are returned as string then you may face issues in JavaScript operations like sorting.

Below code will convert {“miles”: “15.3”} to {“miles”: 15.3}.

JSON.parse(resultJson, function(key, value) { 
    return (typeof value === "object" || isNaN(value)) ? value : Number(value); 
});

OrderBy Pipe in Angular 6

Create new pipe file with below code and save as orderby.pipe.js. Make sure to include that in app.module.ts declaration.

import { PipeTransform, Pipe } from "@angular/core";

@Pipe({
    name: 'orderBy'
})
export class OrderBy implements PipeTransform {
    transform(array: any[], field: string): any[] {
        array.sort((a: any, b: any) =&gt; {
          if (a[field] <b> b[field]) {
            return 1;
          } else {
            return 0;
          }
        });
        return array;
      }    
}

You can then use above pipe with ngFor in HTML code. You do not need to include pipe in component file.

// names object array
names =[{first: 'Peter', last: 'Smith'},
        {first: 'John', last: 'Smith'},
        {first: 'Tony', last: 'Hornet'},
        {first: 'Sarah', last: 'Hornet'},
        {first: 'Vera', last: 'Man'}, ];
<ul>
  <li>
    <div class="single-topic">
       {{oneName.first}} {{oneName.last}}
    </div>
  </li>
</ul>

Debug mobileweb in device

1) Install nodeJs using msi installer: https://nodejs.org/en/
2) Go to command line and check if its installed or not using: npm -v
3) Install weinre using below command: npm install –g weinre
4) Run ipconfig command and note your IPv4 address.
5) Run the debugging server using your dev machine: weinre –boundHost 10.12.0.1
6) Once you run above command it will give you weinre URL like http://10.12.0.1:8080, run that url in browser
7) Under “Target Script” you will find <script>.., copy that line in your mobileweb code.
8) Under “Access Points”, click on “debug client user interface” i.e. http://10.12.0.1:8080/client/#anonymous
9) Now, once you run your mobileweb

Reference: http://people.apache.org/~pmuellr/weinre-docs/latest/Installing.html