Rails/Ruby. Searching for double emails - ruby-on-rails

I am developing an API in Rails 3.
Lately I have seen some user accounts being double. I am not sure how many so I need a way to find out which accounts that are double.
Is there a way, in ruby, to search the entire database and fetch those user accounts that got the same email address (hence double)?
Thankful for all input!

Just open the Rails console (rails c) and type something like this:
Account.group(:email).having('count_all > 1').count
This will return a Hash with email addresses being the key and the number of times it occured as the value. The result will look something like this:
=> #<OrderedHash {"billyjoe#example.com"=>2, "johndoe#example.com"=>2}>
Then, I guess you could take those email addresses and actually get the accounts:
Account.where(:email => "billyjoe#example.com")
To output them all in the console, you could combine both of those like this:
email_hash = Account.group(:email).having('count_all > 1').count
email_hash.each do |email, count|
Account.where(:email => email).each do |account|
p account
end
end

I think if you try to use(for example):
UserAccount.all.group_by(&:email_address).each do |email, record|
#you will get a set of records grouped by email address
end
this will help you (You did not write detailed description of your models but if think you will get the clue)

Related

Rails show record start from db with specific letters

I want to show only those inquiry processes where company name starts from specific letters. I thought I should use start_with? but in the code below I've an error
NoMethodError (undefined method `start_with?'
def call
InquiryProcess.all.includes(inquiry_field_responses: :inquiry_field).select do |process|
process.inquiry_field_responses.select do |inquiry_field_responses|
inquiry_field_responses.inquiry_field.name == 'company_name'
end&.last&.value == start_with?('aaa')
end
end
I would do something like this:
field = InquiryField.find_by!(name: 'company_name')
response_table = InquiryFieldResponse.arel_table
responses = field.inquiry_field_responses.where(response_table[:value].matches('aaa%'))
processes = InquiryProcess.where(id: responses.select(:inquiry_process_id))
First select the field that you want to check the values of. From there select all responses that belong to that specific field and start with 'aaa'. Then select the processes using the responses.
The issue with your current code is that you'll do:
'some string' == start_with?('aaa')
Which should be:
'some string'.start_with?('aaa')
Or more specific to your case:
end.last&.value&.start_with?('aaa')
It's much more easier.
Just use SQL for this:
InquiryProcess.where("company_name LIKE ?", "aaa%")
This shows you all inquiry_processes that company_name starts with aaa

How to check if text contains an #username? - Rails

In my create action in the comments controller I want to check if the comment text contains a "# + username" so I can add it to my public activities.
if #comment.body.include?(' [HERE] ')
maybe User.all.username.any? ?
You better use ruby regex to first find the user name from comment body matching pattern #abc and then user that username query database to find user
#comment.body.scan(/#(\w+)/).flatten.to_a.each do|username|
if User.where(:username => username).any?
# your code here
end
end
or search the users with single database query by passing the array
usernames = #comment.body.scan(/#(\w+)/).flatten.to_a
if User.where(:username => usernames).any?
# your code here
end
This will optimize the db query and will not load all users to memory.
A quick answer:
if User.pluck(:username).any? {|u| #comment.body.include?("##{u}")}
# ...
end
A better answer:
Why not use a javascript library to auto-complete the username? This is more user friendly, and scales better as the User table grows.

Ruby .where to see if array includes a result that doesn't match query.

I'm trying to query an array of signups. Each Signup has a field on it twitter.
The field is an array and at present will only have two items, but can also only have one. The three possible outputs from calling Signup.twitter are:
Signup.twitter => ["No Twitter", "randomhandle"]
Signup.twitter => ["No Twitter"]
Signup.twitter => ["randomhandle"]
I'm trying to use a .where query to only return me handles that have a randomhandle in. If they return ["No Twitter", "randomhandle"] I still want that record to be returned though.
Any help must appreciated,
Thanks.
Try array search methods, like find_all (select is the same) or reject (http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-find_all)
Absolutely agree with the previous answer, but I would do it in 'positive' way, rather than 'negative' so as to keep it clear:
Signup.all.find_all do |signup|
# Use Array.wrap or protect it from `undefined method for nil class`
"randomhandle".in? Array.wrap(signup.twitter)
end
Ultimately, you can do whatever you want.
In case if the twitter field is association you can use where directly:
Signup.where(twitter: Twitter.where(name: "randomhandle"))
Check http://guides.rubyonrails.org/active_record_querying.html
This should work:
only_twitter_users = Signup.all.reject do |signup|
signup.twitter == ["No Twitter"]
end

Rails - find by with two fields using OR instead of AND?

I am familiar with doing a find on two fields:
user = User.find_by_username_and_email(params[:username], params[:email])
However, I would like to retrieve one record where the username OR email equals the same field. Something like:
user = User.find_by_username_or_email(params[:text])
Which I know doesn't work. Is this possible? Any help is a appreciated.
Just to expand on the answer by #xdazz, you can use the following syntax to allow searching any number of fields by the same value without having to repeat the value:
user = User.where('username = :text or email = :text', :text => params[:text]).first
Very useful when you come to search postal address fields, for example.
2.2.1 Placeholder Conditions
You could use .where :
user = User.where('username = ? or email = ?', params[:text], params[:text]).first

How to parse a Mash from LinkedIn to create a Ruby object

I used LinkedIn gem by pengwynn to get authentication from LinkedIn. Everything works fine, and I get a Mash in a callback that looks like this:
#<LinkedIn::Mash all=[#<LinkedIn::Mash company=#<LinkedIn::Mash id=1422 industry="Banking"
name="Company" size="10,001+ employees" ticker="ABC" type="Public Company"> id=2851554
is_current=true start_date=#<LinkedIn::Mash month=12 year=2008> summary="" title="Boss">] total=1>
How can I parse it to something similar to Rails params in order to create a new object from it?
Thank you.
When you receive list of connections of any sort from LinkedIn, you need to get to the list from all. On the object you received from LinkedIn, you have {all, total}. total will give you the number of objects in the array, all will give you all of the objects. So if you wanted to turn the first company into a hash, you would call object.all.first.to_hash. You can iterate through all of them by doing object.all.each {|c| # your block}.
If your own Rails models match the objects being returned from the linkedin gem, you can do:
companies.all.each do |company|
Company.create(company.to_hash)
end
If they don't map 1:1, you can just choose the fields you want:
companies.all.each do |company|
c = Company.new
c.name = company.name
c.year_founded = company.start_date.year
c.ticker = company.ticker
# etc. etc. etc.
c.save
end
You can just call .to_hash to turn a Mash into a Hash (like params).
Source:
https://github.com/intridea/hashie/blob/master/lib/hashie/hash.rb

Resources