Ruby on Rails Undefined method find_by_email - ruby-on-rails

I have a weird issue, I can't seem to find_by_email working in my project, here's the part of my controller where I'm getting the exception. I am using rails 4.0.3
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, notice: "Welcome back!"
else
flash.now.alert = "Email or password is invalid"
render "new"
end
end
I can't stop anything wrong with the code but still getting Action Controller: Exception caught:
NoMethodError in SessionsController#create
app/controllers/sessions_controller.rb:6:in `create'
undefined method `find_by_email' for #<Class:0x007fbdd62179b0>
I'm wondering if there was another way I could troubleshoot this? I've tried using the method manually in the rails console but receive the same issue.

As suggested by many, this is due to missing email column in users table.
If you have not run migrations yet, please do it.

Add email field in users table
Rails 4.1.0 will depreciate custom find by method
Use
User.find_by email: params[:email]
Sooner or later you have to change it.
reference
http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_by

Related

Rails 4.1 can't do the #user_friendship.save in the controller and returns an error

Hi apparently cant save my work in rails 4.1 after adding the state machine gem and doing some more details like when you add someone in the friends i get an error in my controller the #user_friendship.save
this is the controller line
i got this error in my User_Friendships Controller and the line that contains the #user_friendship.save fails every time
def create
if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
#friend = User.where(profile_name: params[:user_friendship][:friend_id]).first
#user_friendship = current_user.user_friendships.new(friend: #friend)
#user_friendship.save
flash[:success] = "You are now friends with #{#friend.full_name}"
redirect_to profile_path(#friend)
else
flash[:error] = "Friend required"
redirect_to root_path
end
end
this is the error that occurs when i add to the user friendship
NoMethodError in UserFriendshipsController#create
protected method `around_validation' called for #<StateMachine::Machine:0x007fe631d43a68>
{"utf8"=>"✓",
"authenticity_token"=>"gPaCH/833buhbi53USaprtbmvFGjNCHE7RYY+DW071s=",
"user_friendship"=>{"friend_id"=>"popo"},
"commit"=>"Yes,
Add friend"}
i am new in rails so can you please explain more so that i can undestand why this is happening and thank!
Apply this patch, Till they fix it, it will work
config/initializers/state_machine_patch.rb
module StateMachine
module Integrations
module ActiveModel
public :around_validation
end
end
end
Do you use the newest version of statemachine? If no, try the newest version of state machine.
https://github.com/pluginaweek/state_machine/issues/295

active admin destroy action

im working in a project writen in ruby on rails and im currently using the active admin gem for its content manager system of my site im just wondering how active admin is using the delete action im trying to overide it but i my code doesent work, i think we are having a problem in how to get the specific line to be destroy
def destroy
#menu = Menu.find(params[:menu_recipe][:menu_id])
#menu_recipe = #menu.menu_recipes.find(params[:id])
#menu_recipe.remove_recipe
#menu_recipe.destroy
redirect_to #reservation, :notice => "recipe destroyed"
end
it comes with a error of
undefined method `[]' for nil:NilClass
Probably params[:menu_recipe] is not set. Try putting params[:menu_recipe] ||= {} at the beginning.
But why is it that you're finding through the Menu, anyway? Can't you just do 'MenuRecipe.find(params[:id])'?

undefined method `activated?'

I'm trying to implement Authlogic in Rails 3 and have just been having headache after headache...I'm extremely new to rails, so please forgive me for not being an expert. I followed the railscast on the subject which has been really helpful, but as soon as i submit my create new user form via the actual website I get this:
undefined method `activated?'
app/controllers/users_controller.rb:37:in `create'
Any help would be SO appreciated...had a headache with this tonight...
Code from create method:
def create
#user = User.new(params[:user])
if #user.save
flash[:notice] = "Registration successful."
else
render :action => 'new'
end
end
If anyone else hits this issue - regenerate your user_session model and fill it with:
class UserSession < Authlogic::Session::Base
def to_key
new_record? ? nil : [ self.send(self.class.primary_key) ]
end
end
This fixed it for me...seems to be an error surrounding that model at the very least so take it back to basics!
The problem for me was the existence of a user_sessions table. If you created the UserSession model through a generator, you have a migration that creates that table.
Simply deleting the table (both in test and development databases) and the migration file solved the problem for me.
Cheers,
-- José

OmniAuth / Rails - You have a nil object when you didn't expect it

I'm getting the following error in my Rails application and I have no idea how to go about debugging or fixing it:
NoMethodError in
AuthenticationsController#create
You have a nil object when you didn't
expect it! You might have expected an
instance of ActiveRecord::Base. The
error occurred while evaluating nil.[]
Rails.root:
/Users/phil/Sites/travlrapp.com
Application Trace | Framework Trace |
Full Trace
app/controllers/authentications_controller.rb:15:in
`create'
The controller is this:
class AuthenticationsController < ApplicationController
def index
#authentications = current_user.authentications if current_user
end
def create
omniauth = request.env["omniauth.auth"]
unless omniauth
redirect_to authentications_url
flash[:notice] = "Could not authenticate via #{params['provider']}."
end
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
elsif current_user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => omniauth['credentials']['token'], :secret => omniauth['credentials']['secret'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
else
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
end
end
def destroy
#authentication = current_user.authentications.find(params[:id])
#authentication.destroy
flash[:notice] = "Successfully destroyed authentication."
redirect_to authentications_url
end
end
OmniAuth used to work fine, then I mashed it up trying to swap to a fork by pchilton which supported flickr. I did this by setting :git => in the gemfile and trying to reinstall but im not confident I ever did it right.
I have now manually removed all omniauth and oa- foo gem files and installed first the current stable (0.1.6) and the git master copy but all errors are the same.
Really at a loss here, nobody I know has any idea what the problem is.
It's probable that omniauth is nil. While you are checking for nil with unless onmniauth, the redirect_to doesn't actually stop the controller code below from executing.
You probably want something like this:
unless omniauth
redirect_to authentications_url
flash[:notice] = "Could not authenticate via #{params['provider']}."
return
end
Now, you still need to figure out why omniauth is nil. For that, make sure you are using OmniAuth correctly by looking at the README. Is /auth/provider/callback routed to AuthenticationsController#create ?
I apologize in advance if you already know this method (you are a php developer after all).
Does rails support php style debugging similar to die() ? I have encountered weird incomprehensible error like this in both yii and kohana php frameworks.
What I do is put a die('AAAAA') at the end of the controller acion, and gradually move it up until IT gets triggered before the error does, that way I know exactly on what line the error was.
Then i move it into whatever function is called on that line and start again.
I don't know if rails supports this kind of raw debug style. Also it would help if the source code for those gems are in noncompiled code so you can insert die() all over the place like that.
You could do something like the equivalent of echo 'AAA'; exit; or something similar.
Also there is also the 'check if a function gets called: die('BBBBB'); :P
If you want to go really advanced there is also
die("AAAAA ".' '.__FILE__.'::Line:'.__LINE__);
This seemed to randomly fix itself. Go Rails!

Rails 2.3.5: flash[:notice] disappears after redirect_to call

Here I've got two controller methods:
def invite
if request.post?
begin
email = AccountMailer.create_invite(#user,url)
AccountMailer.deliver(email)
flash[:notice] = "Invitation email sent to #{#user.email}"
rescue
#mail delivery failed
flash[:error] = "Failed to deliver invitation"
end
redirect_to :action => :show, :id => #user.id
end
end
and
def show
#title = "User #{#user.full_name}"
end
The problem is, when I send an invitation, and get redirected to ./show, I see no messages at all. If I change redirect_to to render, the message appears. Still, isn't it intended for flash to work in the immediate subsequent requests?
BTW, I'm using Rails+Passenger setup, could it be so that redirected request goes to another application instance?
The rescue block is setting flash[:error], not flash[:notice]. Is your view actually rendering both?
Googled better and found this discussion:
http://www.mail-archive.com/activescaffold#googlegroups.com/msg04284.html
The solution is there: replace the plugin with
script/plugin install git://github.com/ewildgoose/render_component.git -r rails-2.3 --force
Though I don't use ActiveScaffold, there is some legacy code that depends on render_component plugin. Updating plugin to branch version worked, though I'm planning to get rid of it completely.

Resources