Browsing the Ruby on Rails category

rails create admin namespace

I needed to create a basic “admin”section for my Rails app.  For now I just verified if I personally was logged in (which I’ve already done).

First I generated a controller/view of a subdirectory “admin” with an action of “users”

rails g controller admin/users
Then create /app/controllers/admin/base_controller.rb with this contents

Your admin/users controller that was just created looks like this:

class Admin::UsersController < ApplicationController
end

Change it to this

class Admin::UsersController < Admin::BaseController
end

Note how now it “inherits” from the Base Admin controller, which has the code that checks if the right user is logged in.  Then put the rest of your code in there; and make sure subsequent admin controllers inherit from the “base” class.

And add this to your routes file:

namespace :admin do
  get “/” => “users#index”
  resources :users
end

And create an “admin” layout in /app/views/layouts/admin.html.erb

Read the article

Rdoc vs md default syntax

I published a recent Rails app on GitHub, and I wanted there to be documentation on how it worked.  I wanted to have links, etc. in there – but when I tried to make a link, it specified the exact code (with parenthesis and brackets).

Turns out the default extension is “.rdoc” for Rails apps; I had to change it to a “.md” extension – “Markdown” – which has a different syntax.

Read the article

Ruby On Rails Face Detect Tutorial

A friend had a need to see if an image had a face in it (like Facebook can auto-detect).  I found a Ruby Gem to do this, but had trouble.

I eventually figured it out; the hardest part / real key being in line 18 in application_controller.rb file

face_detection = original_output[‘photos’].first[‘tags’].first[‘attributes’][‘face’]

 

For the full source code/explanation: https://github.com/stevesohcot/rails-face-detect

Demo: https://rails-face-detect-demo.herokuapp.com

Notes:

  • I was unable to detect a face in an image that was on the same web server as the code
  • When deploying to Heroku, make sure you take out the references to SQLLite (perhaps use PostGres instead)

Read the article

Rails uninitialized constant Google Custom Search Api::GOOGLE_API_KEY

I’m making a Rails app that’s importing data from a Google Search, using this gem.

I was getting this error:

uninitialized constant Google Custom Search Api::GOOGLE_API_KEY

I thought I restarted the server, but apparently not; as, when I closed the Terminal and re-opened it, I didn’t get that error.  But when I did a search, I got no results.

I then did a “raise” on the results and could see a (hidden) message indicating that I didn’t ENABLE my Google Custom Search, so I had to do that.

Read the article

Rails OmniAuth Error – No route matches [POST] “/auth/identity/register”

I was getting this error when trying to implement OmniAuth:

No route matches [POST] “/auth/identity/register”

The problem was that my “omniauth.rb” file in the config folder wasn’t in the “initializers” subdirectory (I wrongfully had it right in that root folder)

Read the article

Rails OmniAuth Identity

Here are the steps I used to set up OmniAuth (Identity)

1 – Add this to your Gem file

gem ‘omniauth-identity’

… and do a bundle install

2 – Create /config/initializers/omniauth.rb with this content

3 – Put this at the top of your routes file:

#Omniauth
match ‘auth/:provider/callback’, to: ‘sessions#create’, via: :all
match ‘auth/failure’, to: ‘sessions#failure’, via: :all
match ‘signup’, to: ‘identities#new’, via: :get
match ‘login’, to: ‘sessions#new’, via: :get
match ‘logout’, to: ‘sessions#destroy’, via: [:get, :delete], as: ‘logout’

4 – Update your application controller – https://gist.github.com/stevesohcot/b161cf3f88eb9b9da3d3 .  This will give some custom functions to check if the user is logged in.

5- Create Sessions controller

rails g controller sessions

Populate with this content – https://gist.github.com/stevesohcot/51d93d68286a1ee1e95e

6 – Create /views/sessions/new.html.erb with this content .  Note, I have extra CSS styling in there using Bootstrap, and there are some javascript validation functions that you may not need.

7 – Create an Identity scaffold, but then delete all the “view” files EXCEPT for new.html.erb ( as in: “new.html.erb” is the only one you’re keeping)

rails g scaffold Identity first_name:string last_name:string email:string password_digest:string

then rake db:migrate

8 – Populate the Identities Controller with this content

9 – Populate the Identities “new” view – this is your “sign up” form. NOTE: this is using Bootstrap for styling, and has some additional javascript not in this file. Specifically, the “Confirm Password” is hidden, so it will automatically be updated to whatever is in the original; and he “Show Password” checkbox toggle

10 – Update Identity Model with this content

11 – Add this to your routes file (BELOW the other OmniAuth code)

resources :identities , only: [:new]

12 – Create User model:

rails g model User provider:string uid:string first_name:string last_name:string email:string user_hash:string

rake db:migrate

Difference between Identity and User:  the Identity model stores user info as the “base” for users who are NOT authenticated from a 3rd party (ex. Facebook, Twitter).  The “User’ model in the app is where you get user information from

13 – Update the User model with this content

14 – Here’ the javascript for some of the advanced user login functionality

“You’re done”

Useful info:

– Link to Sign Up –  <%= link_to “Sign Up”, signup_path, :class => “btn” %>

– Link to Log In –  <%= link_to ‘Log In’, login_path, :class => “btn” %>

– In the view, display the user who is logged in – Hello <%=current_user.email %>

 

 

 

Read the article

rails wont display new view undefined method

I was getting an error in rails about “undefined method” – I had created (from the scaffold) a new method, and I only needed the NEW action to appear.

 

The solution was that in the routes file, you need to specify (at minimum) that the new AND create exist

  resources :feedbacks, only: [:new, :create]

Read the article

rails namespace new action form helper

For my Rails app, I added a namespace.

There were a couple of solutions, but the “right” one should be done by passing in the namespace in as a symbol (with square brackets)

<%= form_for[:admin, @activity] do |f| %>

But that yielded an error.  The problem was that I needed a space between the “form_for” and the opening bracket.

Solution:

<%= form_for [:admin, @activity] do |f| %>

 

Originally, I had:

<%= form_for(@activity, url: admin_activity_type_path) do |f| %>

… but I got ran into a problem with the “new” action trying to render the “show” controller.  The solution I had (with the space typo) is the way to go.

Read the article

Rails app remains running after terminal closed

Usually I just close the command line terminal, and that stops my web server.  I recently switched to using the Foreman Gem, and found that now when I close the terminal, the web app remains running.  This causes some problems in not being able to truly get a fresh start when I’d expect to.

Solution: shutdown the server with Ctrl + C … then you can optionally close the terminal window

Read the article

Rails – setting up environmental variables so passwords aren’t in GitHub

When I push my code to GitHub, I don’t want to upload password/keys for services.  The way around it is to use “environmental” variables.  The true value will be on my local machine, and separately on Heroku’s servers.

Now in my code, I can reference this environmental variable instead of the hard-coded value.

This particular example is for the Segment analytics –

/config/initializers/analytics_ruby.rb

Analytics = Segment::Analytics.new({
write_key: ENV[‘SEGMENT_KEY’],
on_error: Proc.new { |status, msg| print msg }
})

Steps

1) In the project’s folder, create a new file with the extension “.env” (no file name)

2) Populate the file in the format of KEY_NAME_IN_CAPS=VALUE (Note: no spaces around the “=”.  Capital letters for the key name is just a convention for a constant)

3) I added this .env file to my “.gitignore” so that it won’t be checked in to GitHub. I just added these two lines at the end of the file:

# Ignore environmental file
.env

4) Now I had to link it up so that the Rails app knew about the environmental variables.  I had to install the Foreman gem (to my local machine). I ran this on the command line:

gem install foreman

5) Now to start my Rails server/app, I have to use this command:

foreman start

Notes

  • I was previously using Unicorn, which I ran by a shortcut command.  Foreman was smart enough to do this AND set my environmental variables.
  • For me, Foreman was defaulting to running on port 5000.  I wanted to keep the default 3000, so I added this to my .env file: PORT=3000

Now this will work in development (on my machine), I just had to set up Heroku to know the value of the environmental variable.  Run this on the command line; no spaces, and obviously change the key/value to match what was in your .env file

heroku config:set MY_KEY_NAME=the_value_here

You can confirm the current Heroku configuration settings are correct by running:

heroku config

Read the article