I have an email address and I would like to check if it is in different model, in which case, return the id in that model.
I wrote the following:
def find_contact(email)
case email
when !User.find_by(email: email).nil?
return User.find_by(email: email).id
when !Viewer.find_by(email: email).nil?
return Viewer.find_by(email: email).id
else
return "No information"
end
end
When i try with any email, it returns No Information even for the current user.
What am i doing wrong please ?
Yes, this answer is not about case, but it seems that case is not needed here
And I suspect that id as such is also irrelevant. They can be repeated (or not repeated) in different tables
The "No information" string also looks quite strange
Therefore, I would suggest returning a record corresponding to the email. If no such record is found, nil will be returned. And somewhere outside process this nil
def find_contact(email)
User.find_by(email: email) || Viewer.find_by(email: email)
end
Related
I've a variable registered(boolean) in my table User. Because when a connected user want to use an Email, if this email is not existing into the table User, a new line is created in the Users (only with the variable email, and registered = false).
So I would like that when a user registers, he will not be blocked if(email exist && registered == false).
In this case, the password will be replaced, and the variable registered change to true.
I would like to run something like that :
def create
#user_registred = User.find(email: params[user: :email])
if #user_registred.any?
if #user_registred.registred == false
#user = User.update(params[:user])
else
notice: "Email already taked"
end
else
#user = User.new(params[:user])
end
end
I think devise already provide uniqueness on email. Apart from this instead of having another column you can put validation of uniqueness also here. Apart from this you can also set database level uniqueness constraint.
Update :
have a look at the below code.
user = User.where(email: 'test#email.com').first_or_initialize
if user.new_record?
user.save
Do your stuff.
else
user.update_attributes(attributes goes here)
and do your other stuff
end
I'm trying to test my User model's class method #registered_but_not_logged_in(email), which grabs the first user that matches the email that has a confirmed_at entry but has never logged in (which I'm counting with sign_in_count). I'm using rspec with Factorygirl, plus shoulda-matchers v2.8.
Here's the ruby:
def self.registered_but_not_logged_in email
self.with_email( email ).confirmed.never_signed_in.first
end
I've tested this in the Rails console and I know it works as expected so it's not a logic problem on that end, so I'm thinking I'm doing something wrong in my test:
describe User do
# create #user
describe ".registered_but_not_logged_in" do
it "returns a user that matches the provided email who is confirmed, but who has not yet signed in" do
#user.confirmed_at = 2.days.ago
#user.email = "fisterroboto5893#mailinator.com"
result = described_class.registered_but_not_logged_in("fisterroboto5893#mailinator.com")
expect(result).to be_instance_of(User)
end
end
In this example, result is nil. I know that this is a case of #user existing outside the database while the method is actively checking the DB, but I don't know how to handle this while using rspec/factorygirl. Any help is definitely appreciated!
So I'm not 100% sure why what I'm doing is working, but here's the solution that I stumbled across with the help of #nort and one of my coworkers:
it "returns a user that matches the provided email who is confirmed, but who has not yet signed in" do
#user.confirmed_at = 2.days.ago
#user.email = "fisterroboto5893#mailinator.com"
#user.sign_in_count = 0
#user.save!
expect(User.registered_but_not_logged("fisterroboto5893#mailinator.com")).to be_instance_of(User)
end
What I believe is happening is the save! is saving #user to the test database, which is otherwise completely unpopulated as I develop against a different DB. The issue of course being that we can't test data that doesn't exist.
As a bonus, note that expect().to... is the preferred convention for rpsec. Also, described_class I believe would totally work fine, but am preferring explicitness right now since I'm still learning this stuff.
I'm trying to build a registration module where user can only register if their e-mail is already in an existing database.
Models:
User
OldUser
The condition on User will be
if OldUser.find_by_email(params[:UserName]) exists, allow user registration.
If not, then indicate error message.
This is really simple to do in PHP where I can just run a function to execute a mysql query. However, I couldn't figure out how to do it on Rails. It looks like I have to create a custom validator function but seems to be overkilled for a such simple condition.
It should be pretty simple to do. What have I missed?
Any pointer?
Edit 1:
This solution by dku.rajkumar works with a slight modification:
validate :check_email_existence
def check_email_existence
errors.add(:base, "Your email does not exist in our database") if OldUser.find_by_email(self.UserName).nil?
end
For cases like this, is it better to do validation in the model or at the controller?
you can do it as
if OldUser.find_by_email(params[:UserName])
User.create(params) // something like this i guess
else
flash[:error] = "Your email id does not exist in our database."
redirect_to appropriate_url
end
UPDATE: validation in model, so the validation will be done while calling User.create
class User < ActiveRecord::Base
validates :check_mail_id_presence
// other code
// other code
private
def check_mail_id_presence
errors.add("Your email id does not exist in our database.") if OldUser.find_by_email(self.UserName).nil?
end
end
I'd recommend starting with Devise.
See https://github.com/plataformatec/devise
Even if you have unusual needs like these, you can normally adapt it. Once you get to know it, it's extremely powerful, solid and debugged, and you can do all sorts of things with it.
Bellow is just an initial implementation .../app/controller/UsersController for User registration related actions.
def new
#user = User.new
end
def create
#user = User.new(params[:user])
#old_user = User.find_by_email(user.email)
if #old_user
if #user.save
# Handle successful save
else
render 'new' # and render some error message telling why registration was not succeed
end
else
# render some page with some sort of error message of 'new' new users
end
end
Update:
Check out the following resources for more info:
Ruby on Rails Tutorial
Rails: User/Password Authentication from Scratch, Part I/II
I am building a little application in Rails and what I am trying to do now is authenticate a user.
So I got this method in the controller class:
def login
if #user = User.authenticate(params[:txt_login], params[:txt_password])
session[:current_user_id] = #user.id
redirect_to root_url
end
end
Here is the definition of authenticate method (inside the User model class):
def self.authenticate(username, password)
#user = User.where(["username = ? AND password = ?", username, password])
return #user
end
The problem is that I get an error message saying:
undefined method `id' for #<ActiveRecord::Relation:0x92dff10>
I confirm that the user I was trying to log in really exists in the database (besides it tries to get the id of a user and this instruction is wrapped inside an if in case 0 users are returned from the authenticate method).
Why am I obtaining this error message? Knowing that when I change the User.where by User.find it works fine!
Thank you!
User.where("some_conditions") will return an array of User objects ( in simple terms ) , A User.find can return an array or a single object.( I am not sure because i don't see how you are using it )
As far what you see is ActiveRecord::Relation, this is what is returned when we call a find or a where or a order method on Rails 3 Models.
Also, You are storing password as a plain string which is a bad idea, you should use some available rails authentication plugins like Devise or Authlogic.
I have this in my user.rb:
attr_accessor :old_password
def validate
unless password.nil?
errors.add_to_base("Old password entered incorrect") unless self.valid_password? old_password
end
end
I have old_password as a a virtual attribute that has to be validated as matching with the current before updating to a new password. My problem is that upon correct entering ( password == password confirmation and self.valid_password? old_password ) an error will yield and pass me back to the form. The strange part is that the data will actually be updated in the database, and it will not on wrong input; although it will yield the very same error ("Old password entered incorrect"). What on earth am I doing wrong?
Alright, found the problem.
I used a custom update attributes, which used to look like:
def custom_update_attributes(userparams, updater)
unless updater.may_change_user_role_name? self
userparams.delete(:role_name)
userparams.delete(:active)
end
self.update_attributes(userparams)
save
end
The obvious problem here is save, even though I changed my def validate to def validate_on_update this validation has been running on the save action too, and since no old_password is supplied, error will be yielded.