Rails + Geocoder: Get users' objects around another user - ruby-on-rails

My app allows users to see what others are selling (typically objects) around them.
In my first try, I get all objects using:
#objects = Object.all.order( created_at: :desc )
Now, I would like to restrict objects list to objects that are sold around the current user, using Geocoder gem. So I did:
#users = User.nearbys(10)
which gives me users around current user by 10kms. But I have to change the view because now I'm using a list of users instead of a list of objects.
How can I get a list of objects (like in try number 1) in a specific area (like in try number 2)?
Thanks

I finally got it:
#objects = Object.where( user_id: current_user.nearbys(10).map{ |u| u.id } )
Hope it will help.

Related

Removing an item from an in-memory collection

I have a collection that contains a class like:
locations = Location.all
class Location < ActiveRecord::Base
end
The location class has a property: code
I wan to remove an item from the collection if code == "unused".
How many different ways can I do this in ruby?
I am currently doing this:
locations = Location.all.select { |l| l.code != "unused" }
This works great but just wondering what other ways I could do this just for learning purposes (if there big performance advantages in another way that would be good to know also).
Update
Please ignore the fact that I am loading my collection initially from the database, that wasn't the point. I want to learn how to remove things in-memory not simple where clauses :)
You can simply fetch records from your database what you need:
Rails 4 onwards:
locations = Location.where.not(code: "unused")
Before Rails 4:
locations = Location.where("code != ?", "unused")
If you have a collection and you want to reject some items from it, then you can try this:
locations.reject! {|location| location.code != "unused"}
You are doing this the wrong way. In your case, you are retrieving all records from DB and getting an array of records. Then you are looking for records you need in the array. Instead, you should get the records directly from DB:
Location.where("code != 'unused'")
# or in Rails 4 and latest
Location.where.not(code: "unused")
If you need to remove records from DB, you can do it like this:
Location.where.not(code: "unused").destroy_all
If you just want to know what is the best way to remove elements from an existing array, I think you are on the right track. Besides select there are reject, reject!, delete_if methods. You can learn more about them in the documentation http://ruby-doc.org/core-2.3.1/Array.html
There is a related post that might give more information: Ruby .reject! vs .delete_if

Moving items in ActiveRecord_Relation result?

I want to be able to return User.all with current_user as the first result, and the rest sorted alphabetically by user.name.
What's the "Rails" way to do this? I think it's to convert the ActiveRecord_Relation to an array and then use a combo of .insert and .delete_at to move the target User from its current position to the front. Would I want to create a helper method for that? Or is there a completely different approach?
Thanks!
Not the most "railsy" way, but this should work:
users = User.all.append(User.find(current_user.id))
users = (users & users).reverse!
In one query:
users = User.where("id != ?", current_user.id).all.insert(0, User.find(current_user.id))
However, please remember that it's almost always a bad idea to build your site around User.all queries... after 10,000+ users your app will grind to a halt. Wherever you are doing this query you should paginate the results.

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: Get relationship on array of objects

I don't know if there's a good answer for this. Let's say I have:
users = User.where(:location => "Utopia") #=> Returns [user1,user2,user3,user4]
I would like do something like:
users.photos #=> Returns all photos this group of users has
And simply get all the photos back without iterating over them. I ask because each iteration is a DB call. Is there any good way that does a single DB call?
The most straightforward way to do this is to use the eager loader:
users = User.where(:location => 'Utopia').includes(:photos)
That will fetch the users in one pass, then the relationships and their associated photos in another. You can wrap it all up into one call if you either use a JOIN or a subselect, it's your call, but it'll look something like this:
photos = Photo.includes(:user).where('users.location' => 'Utopia')
There's more information available in the Active Record Query Interface documentation in section 12.

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