Rails 4 Devise + Omniauth Github Routing Error - ruby-on-rails-4

I'm using Rails 4.1.1 and I'm trying to create omniauth github with my devise gem in my application. But I get routing error, I'm following Railscast #235 revised on this topic.
Right now, I'm trying to do the same thing Ryan Bates is doing, which is raise omniauth.auth as a yaml to the screen, but I get the error:
No route matches [GET] "/auth/github/callback"
How do I fix this error?
Here you have my routes:
Rails.application.routes.draw do
devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}
root to: 'questions#index'
resources :questions do
resources :answers, only: [:create]
end
resources :users, only: [:show]
#USERS CONTROLLER MY ROUTES
get "adding_likes/(:id)/(:like)/(:current_user_id)", to: "answers#adding_likes", as: :adding_likes
get "add_accept/(:answer_id)", to: "answers#accept", as: :accept
get "leaderboard", to: "users#leaderboard", as: :leaderboard
end
My controller:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def all
raise request.env["omniauth.auth"].to_yaml
end
alias_method :github, :all
end
My user model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :omniauthable
# :recoverable, :rememberable and :trackable
devise :database_authenticatable, :registerable, :validatable, :omniauthable
has_attached_file :avatar, :styles => { :small => "100x100>" }
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
# has_attached_file :superstarbadge, :styles => { :small => "100x100>" }
# validates_attachment_content_type :superstarbadge, :content_type => /\Aimage\/.*\Z/
has_many :questions
has_many :answers
def to_s
email
end
end
Important part of my devise.rb
config.omniauth :github,NOT-VISIBILE,IN-HERE

Basically, you haven't added the routes for it. I think you've missed Ryan add it to his routes file. Just add this:
get "/auth/github/callback" => "yourController#yourAction"
but since you're using omniauth, it's better this way
get "/auth/:provider/callback" => "yourController#yourAction
And add the necessary views for it.

Related

Rails 4: stack level too deep when trying to destroy picture

Hi I have a normal setup of Paperclip and S3 for image uploads in my application, this is the model I use for attachments:
class Picture < ActiveRecord::Base
belongs_to :ofert, dependent: :destroy
has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100>", :large => "600x400#", :morethumb => "50x50#", :ultrathumb => "25x25#" },
:default_url => "https://s3-sa-east-1.amazonaws.com/:s3_bucket/ofert_defaults/:style/brown_hat.jpg"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
validates_attachment_presence :image, :if => :isProduction?
validates_attachment_size :image, :less_than => 5.megabytes
#process_in_background :image, processing_image_url: 'https://s3-sa-east-1.amazonaws.com/:s3_bucket/ofert_defaults/:style/brown_hat.jpg'
end
The above works very well, however, when I try to destoy a picture:
picture.destroy
I get the following error: stack level too deep
but if instead I do the following:
picture.delete
It works, however the above only deletes the record but not the file uploaded to my S3 bucket, any idea?
It is a bug in rails. Read here
Using
belongs_to :ofert, dependent: :destroy
will cause a circular loop (assuming you have a similar line in the associated model 'Ofert' as well)
You can try replacing it with dependent :delete in one of these models or write after_destroy methods in both to manually destroy the associated model.
Read this discussion here on stackoverflow

Testing custom devise session controller using RSpec

I'm using a custom Devise SessionsController:
#custom_sessions_controller.rb
class CustomSessionsController < Devise::SessionsController
end
In my routes.rb devise is set up like this:
#routes.rb
devise_for :custom_users, {
:singular => 'custom_user',
:class_name => 'CustomUser',
:path => "/",
:path_names => { :sign_in => 'login', :sign_out => 'logout' },
:controllers => { :sessions => "custom_sessions" }
}
I would like to write a simple rspec test:
#custom_sessions_controller_spec.rb
require 'rails_helper'
describe CustomSessionsController, :type => :controller do
describe "login" do
before do
setup_controller_for_warden
#request.env["devise.mapping"] = Devise.mappings[:custom_user]
#my_user = FactoryGirl.create(:custom_user) # creates user with valid credentials
end
it "should succeed with valid credentials" do
sign_in #my_user
curr_user = assigns(:current_custom_user)
expect(curr_user).to eq(#my_user)
expect(response).to be_success
end
end
end
In my rails_helper.rb the following lines are present:
require 'devise'
...
RSpec.configure do |config|
...
config.include Devise::TestHelpers, :type => :controller
config.include Warden::Test::Helpers , :type => :controller
...
The problem is that curr_user in the test is alway nil. What am I doing wrong? Or how to test a custom devise session controller? Or how to log in in - other - tests using a custom devise session?
instead of:
describe CustomSessionsController, :type => :controller do
try:
RSpec.describe CustomSessionsController, :type => :controller do
Hope it works!
Using
#controller.current_custom_user
instead of
assigns(:current_custom_user)
seems to work.

Paperclip giving NameError: uninitialized constant Model::ImageUploader

I Have found a similar question:
NameError: uninitialized constant Article::ImageUploader when using Carrierwave on rails 4.1.5
But I have tried the suggestions there:
carrierwave is installed and bundle is complete
And I have double checked my models.
My user model has:
has_one :image, :as => :assetable, :class_name => "User::Image", :dependent => :destroy
And my user creation works find but as soon as I try to access the views it breaks by this code:
<%= link_to image_tag((current_user.image.nil? ? Settings.default_user_image : current_user.image.attachment.url(:thumbnail)) , :style=>'max-width:60px;', :alt=>current_user.full_name, :title=>current_user.full_name), user_path(current_user) %>
I am not sure why this broke, earlier it was working fine, only thing I can think of is, I did bundle once again when my gemfile.lock got conflicts.
This is how I replicate the issue on rails console:
2.1.1 :001 > u = User.new
2.1.1 :002 > u.build_image
NameError: uninitialized constant User::User::Image
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/inheritance.rb:133:in `compute_type'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/reflection.rb:190:in `klass'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/reflection.rb:207:in `build_association'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/associations/association.rb:247:in `build_record'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/associations/singular_association.rb:29:in `build'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/associations/builder/singular_association.rb:18:in `build_image'
from (irb):2
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:90:in `start'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:9:in `start'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:69:in `console'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Please help. I am stuck at a critical point right now.
Path to the file where error is happening is:
/demo/app/views/home/index.html.erb
Image class resides in:
/demo/app/models/user/image.rb
Contents for image.rb
class User::Image < Asset
has_attached_file :attachment, {
fog_credentials: {:aws_access_key_id=>"***", :aws_secret_access_key=>"***", :provider=>"AWS"}, :fog_public=>true, :fog_directory=>"test",
styles: { :thumbnail => "60x60#", :profile => "165x165#" },
storage: :multiple,
path: ":compatible_rails_root/users/files/:id/:style.:extension",
url: "/uploads/posts/files/:id/:style.:extension",
multiple_if: lambda { |user| true },
display_from_s3: lambda { |user| true }
}
validates_attachment_content_type :attachment, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
User mode is simply in
/demo/app/models
Probably, your namespaces are wrong, try to write your classes as follows (note the introduced Users module):
# app/models/users/image.rb
module Users
class Image < Asset
has_attached_file :attachment, { # ...
# ....
end
end
and just modify a line referring to the Image class in User class (the only change is that it's Users::Image now:
# app/models/users.rb
class User < ActiveRecord::Base
has_one :image, :as => :assetable, :class_name => "Users::Image", #...
# ...
end
this (and maybe one restart of the server later) and everything should be fine.

Rails test ActiveRecord error

I initiated the test environment in my rails app, and when I test the user model with the default code, it throws the following error:
Test code:
test "the truth" do
assert true
end
1) Error:
UserTest#test_the_truth:
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry '' for key 'index_users_on_email': INSERT INTO `users` (`created_at`, `updated_at`, `id`) VALUES ('2014-02-01 17:45:51', '2014-02-01 17:45:51', 298486374)
and inside my user model, I have the following associations
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :user_name , :email, :first_name ,:last_name , :presence => true
has_many :invitations
has_many :incoming_friends, -> { where(:status => '1') }, :class_name => "User", :foreign_key => "friend_id", :through => :invitations
has_many :outgoing_friends, -> { where(:status => '1') }, :class_name => "User", :foreign_key => "user_id", :through => :invitations
Firstly, check your user model fixture in test/fixtures/users.yml. If you have empty declarations of one and two:
one: {}
# column: value
#
two: {}
# column: value
it can cause a problems, because there is a lack of attributes. Remove this part or comment it:
#one: {}
# column: value
#
#two: {}
# column: value
And try run it again.

Mongoid Model won't persist has_one via embeds_one relation

I'm having trouble with embeds in a mongoid4-based rails 4 app. I've been looking for an answer everywhere for the past 2 days. So here is the code.
This is a church management app, with a Service model, embedding a team and a band. Each team/band has several roles such as "presidence", "communion" that refer to a user.
My models :
class Service
include Mongoid::Document
...
embeds_one :team, autobuild: true
embeds_one :band, autobuild: true
...
accepts_nested_attributes_for :team, :band
end
class Team
include Mongoid::Document
embedded_in :service
has_one :presidence, :class_name => 'User', autosave: true
has_one :message, :class_name => 'User', autosave: true
...
end
class Band
include Mongoid::Document
has_one :lead, :class_name => 'User', autosave: true
has_one :guitar, :class_name => 'User', autosave: true
...
embedded_in :service
end
class User
include Mongoid::Document
embeds_one :profile
belongs_to :team, :inverse_of => :presidence
belongs_to :team, :inverse_of => :message
belongs_to :band, :inverse_of => :lead
belongs_to :band, :inverse_of => :guitar
def fullname
"#{profile.firstname} #{profile.lastname}"
end
def self.find_by_talent(talent)
self.where("profile.talents.name" => talent)
end
end
The services controller :
# POST /services
# POST /services.json
def create
#service = Service.new(service_params)
respond_to do |format|
if #service.save
format.html { redirect_to #service, notice: 'Service was successfully created.' }
format.json { render action: 'show', status: :created, location: #service }
else
format.html { render action: 'new' }
format.json { render json: #service.errors, status: :unprocessable_entity }
end
end
end
...
def service_params
params.require(:service).permit(:date, :time, :place, :name, :theme, :team => [:id, :precedence, :message ], :band => [:id, :lead, :guitar ])
end
And the form in _form.html.erb :
<%= form_for(#service) do |f| %>
...
<%= f.fields_for #service.team do |tf| %>
<%= tf.collection_select :presidence, User.find_by_talent(:presidence), :_id, :fullname, {:include_blank => "select a person"} %>
<%= tf.collection_select :message, User.find_by_talent(:message), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
<%= f.fields_for #service.band do |bf| %>
<%= bf.collection_select :lead, User.find_by_talent(:lead), :id, :fullname, {:include_blank => "select a person"} %>
<%= bf.collection_select :guitar, User.find_by_talent(:guitar), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
...
<% end %>
When creating a service, everything seems to run fine, but this is what I get in the console :
2.0.0-p195 :001 > s = Service.last
=> #<Service _id: 52ea18834d61631e7e020000, date: "2014-02-02", time: "10:00", place: "Where it's at", name: "My great name", theme: "The service's theme">
2.0.0-p195 :002 > s.team
=> #<Team _id: 52ea18834d61631e7e030000, >
2.0.0-p195 :003 > s.team.presidence
=> nil
Why is s.team.presidence not created ? s.team looks weird, too, with an ending comma...
Here is the content of my rails log :
Started POST "/services" for 127.0.0.1 at 2014-01-30 10:16:51 +0100
Processing by ServicesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ph6lbdHC2FbiANn/fGSzHWprenj3fWKXM40Hrsc5+AM=", "service"=>{"date"=>"2014-02-02", "name"=>"My great name", "theme"=>"The service's theme", "time"=>"10:00", "place"=>"Where it's at", "team"=>{"presidence"=>"52ea18324d61631e81010000", "message"=>"52ea18324d61631e81010000"}, "band"=>{"lead"=>"52ea18324d61631e81010000", "guitar"=>"52ea18324d61631e81010000"}}, "commit"=>"Create Service"}
MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1} runtime: 0.6610ms
MOPED: 127.0.0.1:27017 UPDATE database=service_boot_camp_development collection=users selector={"band_id"=>BSON::ObjectId('52ea18834d61631e7e010000'), "_id"=>{"$nin"=>[]}} update={"$set"=>{"band_id"=>nil}} flags=[:multi]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 0.5800ms
MOPED: 127.0.0.1:27017 INSERT database=service_boot_camp_development collection=services documents=[{"_id"=>BSON::ObjectId('52ea18834d61631e7e020000'), "date"=>"2014-02-02", "time"=>"10:00", "place"=>"Where it's at", "name"=>"My great name", "theme"=>"The service's theme", "team"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e030000')}, "band"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e010000')}}] flags=[]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 2.7460ms
I guess I'm doing something wrong, but I have no clue if it is in the database model or in the form... or anything else...
You will not be able to do it this way. When you create an embedded document, its _id and all of its data are embedded directly within the parent document. This is in contrast to an association, where the document with the belongs_to gets a foreign key which points to its associated parent document. So here, your User documents each have a team_id and band_id, but when the database tries to get the documents, it can't find them, since you can't query directly for embedded documents; you need the parent document first. For more, see the Mongoid documentation.
Another potential issue is that you have multiple belongs_to definitions in the User models. This will also cause an issue, because for each one of those, Mongoid will attempt to create a team_id and band_id. You should name them separately and specify a class name; perhaps names like :presiding_team and :message_team, :lead_band and :guitar_band, etc. This answer should show you what that would look like.
I would recommend making the Team and Band separate referenced documents instead of embedded documents, since you won't be able to reference users effectively while they're embedded.
Hope this helps.