How to get the previously related record? - ruby-on-rails

I have a Feed model that looks like this:
Feed (id, project_id, content)
Given a Feed object like so (3031, 13, 'yada yo ya').
I want to find the Feed item, if any, that is before the feed object listed above. and it has to be for that project_id.
Something like, given #feed.project_id, find all Feed items for that project_id, and return the record previous to #feed = Feed.find(3031) if any.
Complicated right? Ideas?
Thanks.

You could run a query of all feeds for that project prior to the current feed and just pull the last record:
#feed = Feed.find(3031)
#previous_feed = Feed.where("id < ? and project_id = ?", #feed.id, #feed.project_id).order("id").last

Related

Rails Query Unique Items

I have a search bar which works fine but it produces a duplicate every time it shows the correct result.
if params[:nav_search]
#art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).page(params[:page]).per_page(18)
end
Any clue where I'm going wrong?
Try to the following
#art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
You can see this Rails Guide for very well understand
include .uniq
try this,
if params[:nav_search]
#art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).uniq.page(params[:page]).per_page(18)
end
Use uniq or distinct to avoid duplicate records. In your case, you should use distinct:
if params[:nav_search]
#art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
end

Selecting content to feature

in my Rails app users are able to write and publish posts.
On the homepage, I want to feature a couple of posts.
This is what I'm using to select posts at the moment:
posts_controller.rb
favorite_post_ids = [8,2,5]
#favorite_posts = Post.find(favorite_post_ids)
new_post_ids = [1,2,5]
#new_posts = Post.find(new_post_ids)
and then in the view I loop over them to display the posts.
However, once a post is deleted and the controller can no longer find it, I get an error that says
Couldn't find all Posts with 'id': (1, 2, 5) (found 2 results, but was looking for 3)
What's a better way to do this? I was thinking of individual tables, one for new_posts and one for favorite_posts and then do a relationship to posts. In the table I will have post_id referenced.
UPDATE :
I added a bunch of extra columns to posts with different types of featured content all with boolean values defaulted to false. I assign true if I want them featured.
How would you solve this problem?
Make your posts have flag favorite of type boolean. Then you'd select them like this:
#favorite_posts = Post.where(favorite: true).limit(3)
And for new posts, you can use the timestamp
#new_posts = Post.order(created_at: :desc).limit(3)
Look, no hardcoding!
I dont encourage hardcoding. But still if that is your requirement, try
favorite_post_ids = [8,2,5]
#favorite_posts = Post.where(:id => favorite_post_ids)
new_post_ids = [1,2,5]
#new_posts = Post.where(:id => new_post_ids)

How do i not include latest record but all record from an object in rails?

For example if i want to pull all #posts using #posts.all but i dont want to include the very last or latest record from that?
here is what i am trying to do,
#posts = Post.all(Without the very very latest record that was created.)
Basically all record but not the very last record.
I think it is not worth it to try to generate a SQL query that excludes the very last element. Especially a subquery might be slower than just loading all records into an Array and than excluding the last:
#posts = Post.all[0..-2]
Your other example from the comments would look like this:
#contact_prices = #contact.retail_prices.all.order("created_at DESC").load[0..-2]
Another option (depending on the order of your relation) might be to use offset:
#contact_prices = #contact.retail_prices.order("created_at DESC").offset(1)
This is the most direct way I think of doing what you're trying to do:
Post.limit(Post.count - 1)
If you want your query to allow pagination or other LIMIT queries, you could try something like
Post.where("id < ?", Post.last.id)
Lots of answers that will do the trick, but throwing out an additional option:
#posts = Post.where("id != ?", Post.last.id)
One line AR:
Post.where.not(id: Post.last&.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

Order two #variables together by date

I have a messaging system with two tables: Message and MessageCopy, where each time a message is sent it generates a message_copy for each recipient (with info like read, saved, deleted, etc.).
I would like to show a 'conversation' with sent and received messages for my user, and I would like to splice together sent and received messages, ordered by created_at.
Here are my two currently separated relations.
#sentmessages = Message.where("author_id = ? AND project_id = ?", current_user.id, #project.id).order("created_at DESC")
#receivedmessages = MessageCopy.where("recipient_id = ? AND project_id = ?", current_user.id, #project.id).order("created_at DESC")
I'd like to put these together into one relation using Rails if possible rather than MySQL. Thanks!
I hope I understand correctly - you want a single variable that stores these objects ordered by date.
(#sentmessages + #receivedmessages).sort_by(&:created_at).reverse

Resources