Display places 2 weeks or older with Ruby on Rails + PostgresQL - ruby-on-rails

This topic has been covered before, but I am new and trying to understand. My app is designed to store the locations of an item and since time matters, I wanted to create a link for a view that would ONLY show places that are two weeks or older. I understand I should create a method in the model similar to what's below, but I am just confused on this code. I have been trying to find material to read to understand better. The homepage shows all the places, but I want a link to also show 2 weeks or older.
Along with help, I would love any good reads to help me understand better. Thanks so much SO!
def self.recent_places
Place.select("p.*, COUNT(v.id) AS count").where("post.created_at >= 2.week.ago.utc")
end
This is a link to the GitHub.
https://github.com/Mbartlett413/DumpStack

I would recommend using scope over class method though two are mostly the same:
scope :older_than, ->(time) { where("created_at < ?", time) }
Using:
Post.older_than(2.weeks.ago)
Post.older_than(1.month.ago)
Here you go: http://guides.rubyonrails.org/active_record_querying.html#passing-in-arguments

I actually just solved this for my own app, this is the method that I used inside my model:
scope :recent_places, -> {
where(Place.arel_table[:created_at].lt(2.weeks.ago))
}

Related

Independent ActiveRecord query inside ActiveRecord::Relation context

There is some ruby on rails code
class User < ActiveRecord::Base
def self.all_users_count
User.all
end
end
User.all_users_count
returns, for example, 100
User.limit(5).all_users_count
Now it return 5 because of ActiveRecord::Relation context, in despite of i wroute name of class User.all instead simple all
(.to_sql show that query always contains limit or where id or other things in other cases)
So, how can i make context-independent AR queries inside model methods? like User.all and others?
Thank you!
Ps. Or maybe my code has an error or something like this, and in fact User.all inside any methods and context always must returns correct rows count of this model table
This is very weird and unexpected (unfortunately I can't confirm that, because my computer crashed, and have no rails projects at hand).
I would expect
User.all
to create a new scope (or as you call it - context)
Try working around this with
User.unscoped.all
Edit:
I tried it out on my project and on clean rails repo, and the results are consistent.
And after thinking a bit - this is maybe not even an issue - I think your approach could be faulty.
In what scenario would you chain User.limit(2).all_users_count ?? I can't think of any. Because either you need all users count, and you call User.all_usert_count (or just User.count)
... or you need something else and you call User.limit(2).where(...) - there's no point in calling all_users_count in that chain, is it?
And, when you think of it, it makes sense. Imagine you had some different method like count_retired, what would you expect from such call:
User.limit(2).count_retired ?
The number of retired users not bigger than 2, or the number of all retired users in the system? I would expect the former.
So I think one of two possibilities here:
either you implemented it wrong and should do it in a different way (as described above in the edit section)
or you have some more complex issue, but you boiled your examples down to a point where they don't make much sense anymore (please follow up with another question if you please, and please, ping me in the comment with a link if you do, because it sounds interesting)

Rails update database field according to two other fields

So I have 2 fields in my Articles table.
- :vote_up
- :vote_down
I have methods in my app of updating the :vote_up and :vote_down fields that work fine. What I want to do is order my articles by total votes (:vote_up minus :vote_down).
What is the best way to do this. Can I do this directly in the controller with a certain method? Or must I create a :vote_total field that updates automatically according to the values of the other two fields (if so how do you do this).
Many thanks!
Don't do this in your controller. This is meant to be done in your model. Controllers should just use the model.
You can do this in 2 ways:
Solution 1
Try this in your console (rails c)
Article
.unscoped
.select(%q(articles.*, (articles.vote_up - articles.vote_down) AS vote_total))
.order(%q(vote_total DESC))
and the implement it as a scope in your Article class
scope :order_by_total_votes, -> {
select(%q(articles.*, (articles.vote_up - articles.vote_down) AS vote_total))
.order(%q(vote_total DESC))
}
Solution 2
Create a field vote_total for your Article and update it every time one of the vote fields gets updated (use a before_save callback). Then you can do the same as in solution 1, but without the select part.
Suggestion
I would go with solution 2, because amongst others it is faster in queries
Hope this helps.
Thanks #Hiasinho for your direction. I ended up just creating a :vote_total to my Article database and updated it on both my upvote and downvote methods like so
#article.update_attributes(vote_total: #article.vote_total + 1)
Obviously it was a -1 for downvotes.

Rails named scopes

I was trying to refactoring and optimizing me code. In particular, I wanted to reduce the amount of queries going to the database. In my users controller it worked very well but in an other controller, where I tried the same, it didn't. I've searched for some time now for the answer why it didn't work but I can't really answer it.
I've got users, which can subscribe to courses through enrolments. They are connected through has_many :through etc. relationships. The following works:
#users_courses = current_user.courses
#courses = #users_courses.a_named_scope
But in my courses controller the following wont work:
#all_courses = Course.all
#specific_course = #all_courses.specific_course_scope
The scopes are defined in the respective models and work properly. They are not complicated, just "where ... true/false" definitions. Does someone know the problem here? Thanks!
I'm using rails version 3.2 and ruby version 2.
Until Rails 4 you should use scoped method if you want to have ActiveRecord::Relation instance (on which you can call other scopes) returned instead of Array:
#all_courses = Course.scoped
#specific_course = #all_courses.specific_course_scoped
This should work.
If you want to use includes(:courses), you just do it, for example with:
#specific_course = #all_courses.specific_course_scoped.includes(:courses)

Using Garb with GA Management API v3

I installed Sija's fork of garb and am having some issues. The documentation appears to be a bit outdated as some things have been deprecated.
I have the following code (ignore the fact that it's horribly unsecure):
extend Garb::Model
metrics :pageviews
dimensions :page_path
Garb::Session.login('XXXXXX#gmail.com', 'mypassword')
profile = Garb::Management::Profile.all.detect { |p| p.web_property_id == 'UA-XXXXX-1' }
puts profile.visits
When I run this, I get undefined method visits. I also tried this code on StackOverview, and it returned undefined method results. I'm guessing these are due to the new GA Management API v3 changes, but does anyone know the new way to access pageviews/visits?
I'm trying to query pageviews by date in the end.
Thanks for any help!
You need to create a class extending Garb::Model (https://github.com/Sija/garb#define-a-report-class). Btw, documentation has been updated to work with the newest version of the gem.
Here is an example:
class Report
extend Garb::Model
metrics :pageviews
dimensions :pagePath
end
Edit: Thanks for the edit! That was my first ever post :)

fullcalendar with rails - limit results to a range

I've got fullcalendar working with a small rails app (yeah) but it's sluggish because the find in my controller is finding ALL the records before it renders the calendar. I'm using a JSON approach. The field names I'm using are starts_at and ends_at. This (in the index method of the assignments_controller) works:
#assignments = Assignment.find(:all, :conditions => "starts_at IS NOT NULL")
But, as I said, it's pokey, and will only get worse as more records get added.
So this is clearly more of a rails question than a fullcalendar question: I can't figure out how to get fullcalendar to initially display the current week (when no parameters have been sent) and then accept parameters from next/previous buttons while, in either case, only looking up the relevant items from the database.
Oh - this is rails 2.x, NOT 3.
Thanks for any pointers.
Please ignore this question.
It turned out to be an issue with Date format inconsistencies between JavaScript (Epoch) and Ruby. At least that's what I think at the moment.
I'm still scratching my head, trying to figure out how exactly I "fixed" it, but it seems to be working.
I was aware of this project: http://github.com/bansalakhil/fullcalendar
but it took me ages to get the nuance of Time.at figured out.
I must say, Time is a tricky thing.
In real life as well as in code.
Thanks to everyone who gave my (misguided, as it turned out) question a glance.

Resources