Help doing a dynamic sort? - sql

I have a notifications table which contains different types of notifications for different events.
Inside the table is a notifications_type:string column that contains the type of notification, i.e. "foo" or "bar" or "oof"
I want the user to be able to select what notifications they want to display, so there are checkboxes below the result that correspond to prefs_display_foo:boolean, prefs_display_bar:boolean in the User model.
What is an elegant way for me to set the :conditions in the find to properly display the sorted results? Also, currently I have it as a method in the User model, but how would I do it as a has_many :notifications, :conditions => .....

You could try this
leave the has_many without any conditions and then create a named_scope to handle the preferences, this code is untested
class User
has_many :notifications
def notification_preferences
list = []
list << 'Foo' if prefs_display_foo
list << 'Bar' if prefs_display_bar
# etc...
return list
end
end
class Notification
belongs_to :user
named_scope :preferred,
lambda { |preferences| {
:conditions => ["notifications_type IN (?)", preferences]
}
}
end
# ...
user = User.find(1)
notifications = user.notifications.preferred(user.notification_preferences)

Related

Find cards with today date when user receive mails in RoR

Every day I need to send letters to users with today's tasks.
For do this I need to find all users who are allowed to send letters, and among these users to find all cards that have a deadline today. The result is three array elements with a nil value. How is this better done and right?
#users = User.all {|a| a.receive_emails true}
#user_cards = []
#users.each_with_index do |user, index|
#user_cards[index] = user.cards.where(start_date: Date.today).find_each do |card|
#user_cards[index] = card
end
end
My user model:
class Card < ApplicationRecord
belongs_to :user
# also has t.date "start_date"
end
My card model:
class User < ApplicationRecord
has_many :cards, dependent: :destroy
# also has t.boolean "receive_emails", default: false
end
Something like #cards_to_send = Card.joins(:users).where("users.receive_emails = true").where(start_date: Date.today)
Have a look at https://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables for the docs on how to query on a joined table.
You could do this with a SQL join like this
User.joins(:cards).where(receive_emails: true, cards: { start_date: Date.today })
https://guides.rubyonrails.org/active_record_querying.html#joining-tables

Many to many relationship with ability to set a state (active)

I have a fully working (for some time now) many-to-many relationship in my Rails application.
Instructors has many Schools (through SchoolsToInstructorsAssociations)
Schools has many Instructors (through SchoolsToInstructorsAssociations)
At this time, I would like the ability to have an "active state" in addition to simply adding or removing an Instructor from a School or a School from an Instructor.
I want an Instructor to be set as inactive before being removed completely at a later point (or reactivated).
My first thought was to add an 'active' boolean to the relationship model (SchoolsToInstructorsAssociations), but there's no simple way to access this attribute to update or query it).
My second thought was to simply create another relationship model with the 'active' attribute, but it's redundant and something extra I have to track.
Maybe a custom many-to-many module? Create a SchoolsToInstructorsAssociations controller?
class Instructor < ActiveRecord::Base
has_many :schools_to_instructors_association
has_many :schools, :through => :schools_to_instructors_association
end
class School < ActiveRecord::Base
has_many :schools_to_instructors_association
has_many :instructors, :through => :schools_to_instructors_association
end
class SchoolsToInstructorsAssociation < ActiveRecord::Base
belongs_to :user
belongs_to :school
end
I also plan to create a history record each time an instructors 'active' state changes or an instructor is removed or added to a school. Not asking how to do this, but wondering if it could be used to track an instructors 'active' state.
class SchoolsController < ApplicationController
def instructors_index
#school = School.find(params[:id])
instructors = find_instructors
#active_instructors = instructors[0]
#inactive_instructors = instructors[1]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #schools }
end
end
private
def find_instructors
active = []; inactive = []
#school.instructors.each do |s|
if SchoolsToInstructorsAssociationRecord.where(user_id: s, school_id: #school)[0].active?
active << s
else
inactive << s
end
return [active, inactive]
end
end
end
class SchoolsToInstructorsAssociationRecord < ActiveRecord::Base
default_scope order('created_at DESC')
attr_accessor :user_id, :school_id, schools_to_instructors_association_id, :active
end
Sounds like you can accomplish what you're trying to do with scopes. Add a boolean column for 'active' as you described for the 'Instructor' class, then you can add scopes for it:
class Instructor < ActiveRecord::Base
...
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
...
end
Then for a given School, you can get the active (or inactive) instructors for that school:
#school.instructors.active
=> SELECT "instructors".* FROM "instructors" WHERE "instructors"."school_id" = <id> AND "instructors"."active" = 't'
If you wanted to do some operations on all the inactive instructors (like destroy them, as an example), you could do:
Instructor.inactive.map(&:destroy)
And you can of course write whatever custom methods you want for the Instructor or School classes.

Rails 3: Polymorphic conditioned query

I've got the following models:
class Notification < ActiveRecord::Base
belongs_to :notificatable, polymorphic: true
end
class BounceEmailNotification < ActiveRecord::Bas
has_one :notification, :as => :notificatable, :dependent => :destroy
end
class UserNotifierEmailNotification < ActiveRecord::Base
has_one :notification, :as => :notificatable, :dependent => :destroy
end
As you can see, a notification can be of type "bounce email notification" or "user notifier email notification". The BounceEmailNotification model has a event string attribute. What if I want retrieve all user notifier email notifications and all bounce email notifications which have a specific event value, ordered by created_at?
Something like this (using squeel):
(Notification.joins{ notificatable(BounceEmailNotification) }.where('bounce_email_notifications.event' => 'error') + Notification.joins { notificatable(UserNotifierEmailNotification) }).sort_by { |n| n.created_at }
will work, but I don't want to use Ruby to order the notifications. What can I do? Thanks
Try this.
Notification.joins('left outer join bounce_email_notifications on notifications.notificatable_id = bounce_email_notifications.id and notificatable_type = "BounceEmailNotification"').
where("bounce_email_notifications.event = ? or notificatable_type = ?",'error',UserNotifierEmailNotification.to_s).
order('notifications.created_at')
This is using active record 3.2 but I guess it should work in rails 3.
I have not used squeel cant comment much on how to use it with squeel but this can give you a brief idea.
In squeel I came up with something like this ( NOT TESTED) created by using squeel docs
Notification.notificatable{notable(BounceEmailNotification).outer}. where{
{ ('bounce_email_notifications.event'=>'error') | (:notificatable_type=>UserNotifierEmailNotification.to_s) }
Conceptual steps
left join on the bounce_email_notifications to get all bounce_email_notifications and and non bounce_email_notifications notification in result
check if the bounce_email_notifications.event = event
or
notificatable_type = 'UserNotifierEmailNotification' for all UserNotifierEmailNotification records
sort the records by notifications.created at
Hope this helps.

Rails 3 geocoder and the filtering an object

I'm trying to get the geocoder gem to work on an object that has been filtered using a has_many relationship
like so
user.rb
has_one :profile
has_many :roles
name:string
profile.rb
belongs_to :user
latitude,latitude:float, address:string, city:string
role.rb
belongs_to :user
name:string
the problem I'm having is I need to filter the roles to say id => 3
so we have
#limitrole = User.includes(:profile, :roles).where('roles.id' => 3)
this returns an object of limited roles, now grab the profile that contains the geocode stuff
#profiles = #limitrole.collect { |user| user.profile }
This returns an object of addresses limited to the users role
But this won't work
#findlocations = #profiles.near('city, country', 20) (city and country being arbitrary values)
Yet this will work
#findlocations = Profile.near('city, country', 20)
#profiles should be the same as Profile (both objects) it's just #profiles has been filtered.
How do I get this to work?
This might not be railsy but this is how I got it to work
first grabbing the form fields
#findaddress = params[:profile][:profileaddress] + ", " + params[:profile][:profilecity]
Next I grabbed a list of the users based on their role
#limituser = User.includes(:profile, :roles).where('roles.id' => 3)
next using the geocoder (railscast #273) plugin I create a list of all the geocoded addresses that are near the locations specified in the form (#findaddress) and grab the user_id
#findlocations = Profile.near(#findaddress, 20).pluck(:user_id)
Now I can create a list of users filtered by their role and address specified by a form field
#filteruser = #limituser.where(:id => #findlocations)

Rails 3 ActiveRecord Query questions

I've implemented "following" function. Showing "people user A is following" was simple, but showing "people who are following user A" is giving me troubles.
I have follow_links, which have id, user_id, and follow_you_id column. When user A begins following user B, the columns will be like (user_id = A, follow_you_id = B).
To show users that A(#user) is following, I can simply do
#follow_yous = #user.follow_yous
But I'm not sure how to show users who are following A(#user)
To do this, I first found all the related links.
#follow_links = FollowLink.where(:follow_you_id => #user.id)
Now I thought I could just do #follow_mes = #follow_links.users, but it says user is an undefined method. So I guess I can either call user.follow_yous or follow_you.users.
My next approach was
#follow_links = FollowLink.where(:follow_you_id => #user.id)
#follow_mes = User.where(:id => #user.id, :include => #follow_links)
I intended to find all the User objects that had the provided #follow_links objects, but I think the syntax was wrong. I couldn't find a decent solution after a bit of research. I'd appreciate any help.
Update:
FollowLink model
belongs_to :user
belongs_to :follow_you, :class_name => "User"
You can use joins like this:
#users = User.joins(:follow_links).where(:follow_links => { :follow_you_id => #user.id })
you can use following:
#follow_links = FollowLink.where(:follow_you_id => #user.id)
#follow_links.collect(&:user) # :user should be the name of your relation to user in your followlink model
=> [User1, User2,...]