How to select all of a unique attribute - ruby-on-rails

I would like to find all the Records that have unique email addresses. I am trying to perform this :
#uniq_referrals = []
CardReferral.all.select{|a| #uniq_referrals << a.email}
#referral_count = #uniq_referrals.uniq.each{|a|CardReferral.find_by_email(a)}
But I would like to do it in a single call. Is that possible?

You can use:
CardReferral.select("distinct(email), other_field_you_need")
where other_field_you_need it's a list of field name you need to use from the objects you get from ActiveRecord.
To get the count of unique email record you can use:
CardReferral.count("distinct(email)")

I would like to find all the Records that have unique email addresses. I am trying to perform this :
#uniq_referrals = []
CardReferral.all.select{|a| #uniq_referrals << a.email}
#referral_count = #uniq_referrals.uniq.each{|a|CardReferral.find_by_email(a)}
But I would like to do it in a single call. Is that possible?
I think that it would help you:
Model.group("email")
when we group all the record by email id then you will find all the record that have uniq email. if some record have same id then you will get first record.
please prefer to image for more understanding.
If you could not get yet, then i will explain elaborate more.

Related

How to get only one db record from couple of same?

I have records in the db table that can differ only by ids and creation/update time. How can I get only the unique records?
I tried this way, but it didn't work:
msg_to_user = user.messages.new_messages.uniq
I'll explain. User can follow post manually but also same post can be followed by user automatically. So I want to send only one message if post have been commented by someone.
1747 test message TamadaTours 12 new 2016-01-29 06:14:04.736869 2016-01-29 06:48:55.948529 32964382
1748 test message TamadaTours 12 new 2016-01-29 06:14:04.741184 2016-01-29 06:48:55.951371 32964382
All records in the database are uniq (at least because of ID column, which by default has a uniq constraint).
You would want to use DISTINCT:
Model.select('DISTINCT column_name1, column_name2')
Your question is flawed...
The point of having an id... otherwise known as primary_key... in a relational database is so that you can actively identify the unique records you want:
A primary key uniquely specifies a tuple within a table. In order for an attribute to be a good primary key it must not repeat
When you write... "How can I get only the unique records" ... the answer is to pull only the records based on their id.
If you refine your question to what you really want...
I want to send only one message if post have been commented by someone
--
In other words, you want to pull a collection of unique user_ids (no duplicates), to which you can send new messages?
To do this, you can use...
#recipients = Message.select(:user_id).distinct #-> all unique user_ids
If you're trying to pull the "new" messages for a user, but only show the first (if they're the same), you'll want to use something like the following:
#msg_to_user = user.messages.new_messages.uniq(:title)
Ref
A better pattern to implement would be to validate the uniqueness of new messages:
#app/models/message.rb
class Message < ActiveRecord::Base
validates :user_id, uniqueness: { scope: :message_id } #-> replace message_id with other unique identifier
end
This would ensure only one new message is present for a user.
you can also use group by in your query like this
Model.all.group("column_name")
One way to extract the data but get rid of the ORM context.
# maps every record to hash, remove the ID entry and then removes duplicates
msg_to_user = user.messages.new_messages.attributes.map { |e| e.except('ID') }.uniq

Count from associate table

I want to have some stats from my app, User can publish post that I call Idee, and I want to know how many user have publish at least one idee.
I'm assuming that should be something like:
#total_user_active = User.where(idee.size >= 1).count
But this doesn't work.
It's user who is in table idee so maybe I should count how much unique user_id are in this column but how?
You can do the following:
#total_user_active = Idee.distinct.count(:user)

remove specific record from array of records all in rails

I am implementing search functionality in rails. When i search for users, the logged in user who is searching also comes in search. I want to avoid it.
This is in my search_method in controller
#matchedUsers = InUser.where("first_name like ?", "%#{params[:searchfnameInput]}%")
And i have user id in session[:user_id]. I want to exclude the record having id==session[:user_id] from #matchedUsers?
Thanks and Regards
Add another where clause to your query:
#matchedUsers = InUser.where("id<>?", current_user.id).where("first_name like ?", "%#{params[:searchfnameInput]}%")
The "id<>?" says "exclude the user with this ID".

Rails using a variable find condition

I am using Braintree for managing subscriptions in my Rails app.
I have a Subscription model that stores the braintree customer ID and subscription ID.
I want to filter active subscriptions in my Subscription model. So far I have
def find_active_subscriptions
#active_subscriptions = Braintree::Subscription.search do |search|
search.status.is "Active"
end
But now I want to use the subscription IDs in #active_subscriptions to find all of the objects in my local Subscription model with the same subscription IDs and put that into a variable such as #local_active_subscriptions.
The reason I have to do this is to use the local info to access Braintree::Address and only pull active addresses.
Thanks for the help.
One you have the #active_subscriptions you can collect all of the ids into an array and pass them right into the find method of your local Subscription model. I don't know what attributes you are using here, so I'm just making some guesses:
#active_subscription_ids = #active_subscriptions.collect(&:subscription_id)
#local_active_subscriptions = LocalSubscriptionModel.find(#active_subscription_ids)
I'm not sure what Braintree::Subscription.search returns, but if it's something akin to ActiveRecords, could you use something like:
#local_active_subscriptions = Subscription.where("id IN(?)", #active_subscriptions.map{ |act_subs| act_subs.id })
The .map function should put all the IDs into an array, and then ActiveRecord query would look for all the Subscriptions in your subscriptions table whose ID is in that array.
I'm not certain about mapping on Braintree::Subscriptions; I've never used that.
Edit
Like ctcherry said, you can also do the search with find. And I guess collect is good for mapping the ids into an array too. You could also maybe use #active_subscriptions.map(&:id)

how to store facebook friends to DB (newbie)

i'm creating a facebook-app for university project and i'm trying to store all my friends in the DB.
By using the API-syntax "me/friends" i get a facebook-respond looking like this:
{"data"=>[{"name"=>"Albert Einstein", "id"=>"11111111"}, {"name"=>"Max Mustermann", "id"=>"222222222"}, {"name"=>"Just Another Name", "id"=>"333333333"}]}
I believe its a json-object, but i'm not sure.
Question: How can i save the data, i need a DB with all the User-IDs of my friends.
Thx!
Edit:
Hey, this is what i have searched for. But i still get an error and don't know why.
My code:
def insert_1
fb_friends = rest_graph.get('me/friends')
fb_friends[:data].each do |f|
#friend = Model.new(:name => f["name"] )
#friend.save
end
end
I get an Heroku error (We're sorry, but something went wrong.)
You have two options -
Option 1-
You can create a friends table which will belong to users table. If a user has 200 friends, it will create 200 entries in friends table all belonging to the user via has_many-belongs_to relationship. For storing data, you just have to iterate over facebook friends hash and then save each of them separately
Pros : You can search for any friend separately.
Cons : There will be so many of friend entries. Saving them will take time, if somebody has many friends(say 500-700). Repeating entries will be created for mutual friends.
Options 2
You can add a friends column in your users table and declare this in your user.rb
serialize :friends
This way, you just have to pass a hash object to friends attribute of user table, and rails will save that in yaml format for you. When you will do #user.friends, rails will again convert that yaml formatted data to hash object and return it.
Pros : There will be only one query to save all users. You can iterate through this hash to show list of all friends.
Cons : You can't update them separately, you will update all together. Not good if you want to store some other information in relation to user's friends.
Update
as per your code example above
fb_friends = #your logic to get data as shown above.
fb_friends[:data].each do |f|
#friend = Friend.new(:name => f["name"],:fb_user_id => f["id"] )#creating Friend model obj.
#friend.save
end

Resources