Category

Category: Ruby on Rails

Uploading Rails App with MongoDB to Heroku

heroku

  1. Navigate to your git repository from your computer
  2. Open Gemfile then change gem ‘sqlite3’ to gem ‘pg’
  3. Run the command: “bundle install”
  4. Ensure the config/database.yml is using the postgresql adapter. by changing all “sqlite3” instance to “postgresql”
  5. At the end of Gemfile add:
    ruby “2.3.1”
    – or check version using ruby -v
  6. Login to your heroku account
    $ heroku login
  7. Create a project, CD to where your git project is located in your local computer then type in:
    $ heroku create
    – prepares Heroku to receive your source code.
  8. deploy your code by running the command:
    $ git push heroku master
  9. The application is now deployed. Ensure that at least one instance of the app is running:
    $ heroku ps:scale web=1
  10. Run the database migration:
    $ heroku run rake db:migrate
  11. Now visit the app at the URL generated by its app name. As a handy shortcut, you can open the website as follows:
    heroku open
  12. Do mongodb installation, see instructions bellow:

Installing mongodb Add-on

  1. Run the command: heroku addons:create mongolab:sandbox
  2. Run the command bellow to ensure we have MONGO_URI on our heroku config:
    $ heroku config
    It shows something like this:
    MONGODB_URI: mongodb://heroku_1c3dj371:6ncboo79ofhq5kg49ugiihe5th@ds035856.mlab.com:35856/heroku_1c3dj371
  3. Add production DB connection in your config/mongoid.yml:
    1
    2
    3
    4
    5
    6
    7
    production:
        clients:
            default:
                uri: <%= ENV['MONGODB_URI'] %>
            options:
                skip_version_check: true
            safe: true
  4. Commit and push your code to heroku.

To commit a code to Heroku

  • Almost every deploy to Heroku follows this same pattern. First, add the modified files to the local git repository:
    $ git add .
  • Now commit the changes to the repository:
    $ git commit -m “Demo”
  • Now deploy, just as you did previously:
    $ git push heroku master
  • Finally, check that everything is working:
    $ heroku open

Others Notes

  1. You can view information about your running app using one of the logging commands in real time using:
    $ heroku logs –tail
  2. If you changed the name of your heroku app from heroku website, you can
    perform the following command to update your local git project connection
    1. $ git remote rm heroku
    2. $ heroku git:remote -a NEW_NAME_OF_YOUR_APP

Setting up Bcrypt for Rails on Windows

You probably end up here because you are looking for a way to install bcrypt in your Windows machine. I needed bcrypt for authentication in my Rails application, I struggled a little bit trying to get it working on rails latest version. You might have a similar error on your console like the one bellow:

C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-4.0.0/lib/active_support/depen dencies.rb:228:in require: 126: The specified module could not be found. – C :/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bcrypt-ruby-3.1.11-x64-mingw32/lib/bcrypt_ext.so (LoadError)

Let’s fix that.

Note: This tutorials is using gems 2.3.0 at the time it was created, which might be different from the current version that you are using. You can simply change ALL “2.3.0” on the commands I used for this tutorial to the version you are currently using.

  1. Make sure you have the latest version of Ruby installed on your computer. You can download Ruby for Windows from this link: http://rubyinstaller.org/downloads/
  2. Next is you need to navigate to your rails application then open up your Gemfile and uncomment  gem ‘bcrypt’
  3. Then run bundle install from your terminal to install the bcrypt dependecy.
  4. If you are currently utilizing bcrypt in your application, when you run using rails server you will get an error similar to the error code bellow:
    • C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-4.0.0/lib/active_support/depen dencies.rb:228:in `require’: 126: The specified module could not be found. – C :/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bcrypt-ruby-3.1.11-x64-mingw32/lib/bcrypt_ext.so (LoadError)
  5. CD to your gem directory:  C:\Ruby23-x64\lib\ruby\gems\2.3.0\gems\bcrypt-3.1.11-x64-mingw32\ext\mri
  6. Run ruby extconf.rb
  7. Run make
  8. Run make install 
    • This command will generate bcrypt_ext.so
  9. Copy the generated file “bcrypt_ext.so” to C:\Ruby23-x64\lib\ruby\gems\2.3.0\gems\bcrypt-3.1.11-x64-mingw32\lib\2.3
    • If the folder “2.3” (or whatever version you are using)  is not present, simply create it then paste the file “bcrypt_ext.so” in it.
  10. Restart rails, you will see that the bcrypt_ext.so (LoadError) message is gone.
  11. Congratulations, you just have configured bcrypt in your Windows machine.

If you are experiencing problems with the command: make being unrecognized in your terminal –  it means you do not have DevKit installed in your Windows machine. You can follow the tutorial bellow to install DevKit and associate it with your Ruby installation.

  1. Download DevKit from here: http://rubyinstaller.org/downloads/
  2. Extract the contents of DevKit, preferably under “C:/RubyDevKit”
  3. cd C:\RubyDevKit
  4. ruby dk.rb init
  5. ruby dk.rb install
  6. devkitvars.bat

Ruby on Rails Pagination

I recently started coding with Ruby on Rails, one of the things that I wanted to create is a simple blog. Displaying the blog posts was simple enough, but later on the page started getting too long, so I figured I need to implement a simple pagination. In this tutorial I am going to show you how I did it, let’s get started.

We are going to query the data using Rails’ Active Record Query Interface then manupulate the result to show how many items should be displayed to the screen as well as the logic of the navigation that your users are going to use to to browse through the your posts. Assuming you have a “article” table already setup with a controller that looks like the following:

1
2
3
4
5
6
7
8
class ArticlesController < ApplicationController
    def index
    end
   
    def show
    end
    ...
end

Let’s add some logic to the index method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class ArticlesController < ApplicationController
   
    include ActionView::Helpers::TextHelper
   
    def index
        @pagination_content = ""
        @page_number = params["pageno"] ? params["pageno"].to_i : 1
         
        @page = @page_number
        @cur_page = @page
        @page -= 1
        # Set the number of results to display
        @per_page = 3
        @previous_btn = true
        @next_btn = true
        @first_btn = true
        @last_btn = true
        @start = @page * @per_page
       
        @pagination_content = ""
        @pagination_nav = ""
       
        @all_blog_posts = Article.limit(@per_page).offset(@start).order('title ASC')
        @count = Article.all.length
       
        if @all_blog_posts.present?
            @all_blog_posts.each do |post, value|
                @pagination_content += "
                    <h4>#{post.title}</h4>
                    #{truncate(strip_tags(post.text), :length => 500)}
                "

            end
        else
            @pagination_content += "<p class='bg-danger p-d'>No results</p>"
        end
       
        # Optional, wrap the output into a container
        @pagination_content = "<div class='cvf-universal-content'>#{@pagination_content}</div><br class = 'clear' />";

        @no_of_paginations = (@count.fdiv(@per_page)).ceil
       
        if @cur_page >= 7
            @start_loop = @cur_page - 3
            if @no_of_paginations > @cur_page + 3
                @end_loop = @cur_page + 3
            elsif @cur_page <= @no_of_paginations && @cur_page > @no_of_paginations - 6
                @start_loop = @no_of_paginations - 6
                @end_loop = @no_of_paginations
            else
                @end_loop = @no_of_paginations
            end
        else
            @start_loop = 1
            if @no_of_paginations > 7
                @end_loop = 7
            else
                @end_loop = @no_of_paginations
            end
        end

        # Pagination Buttons logic    
        @pagination_nav += "
            <div class='pagination-container'>
                <ul>"


        if @first_btn && @cur_page > 1
            @pagination_nav += "<li class='active'><a href = '#{@current_page_url}?pageno=1'>First</a></li>"
        elsif @first_btn
            @pagination_nav += "<li class='inactive'>First</li>"
        end

        if @previous_btn && @cur_page > 1
            @pre = @cur_page - 1
            @pagination_nav += "<li class='active'><a href = '#{@current_page_url}?pageno=#{@pre}'>Previous</a></li>"
        elsif @previous_btn
            @pagination_nav += "<li class='inactive'>Previous</li>"
        end
       
        for @i in @start_loop..@end_loop do
            if @cur_page == @i
                @pagination_nav += "<li class = 'selected'>#{@i}</li>"
            else
                @pagination_nav += "<li class='active'><a href = '#{@current_page_url}?pageno=#{@i}'>#{@i}</a></li>"
            end
        end

        if @next_btn && @cur_page < @no_of_paginations
            @nex = @cur_page + 1
            @pagination_nav += "<li class='active'><a href = '#{@current_page_url}?pageno=#{@nex}'>Next</a></li>"
        elsif @next_btn
            @pagination_nav += "<li class='inactive'>Next</li>"
        end

        if @last_btn && @cur_page < @no_of_paginations
            @pagination_nav += "<li class='active'><a href = '#{@current_page_url}?pageno=#{@no_of_paginations}'>Last</a></li>"
        elsif @last_btn
            @pagination_nav += "<li class='inactive'>Last</li>"
        end

        @pagination_nav = "#{@pagination_nav}
                </ul>
            </div>"

       
        @output = "
            <div>#{@pagination_content}</div>
            <div>#{@pagination_nav}</div>
        "

    end                          
end

On your view/articles/index.html.erb file, we simply output the pagination by calling the @output variable:

1
<%= raw(@output) %>

Here’s a neat CSS code that you can use to style your navigation:

1
2
3
4
5
6
7
8
.pagination-container  { margin-top: 15px; }
.pagination-container ul { margin: 0; padding: 0; }
.pagination-container ul li { display: inline; background: #FFF; color: black; }
.pagination-container ul li.active a:hover { background: #1E8CBE; color: white; text-decoration: none; }
.pagination-container ul li.inactive { background: #d0d0d0; }
.pagination-container ul li.selected { background: #1E8CBE; color: white; }
.pagination-container ul li a { color: #1e8cbe; }
.pagination-container ul li a, .pagination-container ul li.inactive, .pagination-container ul li.selected { margin: 3px; padding: 4px 8px; }

 

The output

Here’s how it will look like when you refresh your page:
 
ruby-on-rails-pagination