Rails model has_many order desc group by only containing model - group-by

post.similarities.order("similarity DESC").group_by(:afterscholar_id).first(4).each_with_index
My post has similarities, and I need to be searching exclusively through the ones that contain anything more than 'nil' in the variable afterscholar_id

Related

Microsoft Master Data Services 2016 Additonal Domain Atrribute Referencing

Is it possible to reference additional columns apart from the 'Code' and 'Name' columns when using a domain attribute in an entity?
E.g. A person entity has a code of '1' and a name of 'Smith' and a Gender of 'Male'
In a customer entity there is a domain value referencing the person entity which displays the following 1 {Smith}. The users would like an additional read only attribute which would copy the Gender value of 'Male' into the customer entity based on the domain value. Can this be done using out of the box MDS UI?
I know this is duplicate data and breaks normal form but for usability this would be useful. It would be the equivalent of referencing additional columns in an MS Access drop down list.
Many thanks in advance for any help
This is not possible with the standard UI. One option would be to develop a custom UI where you can handle these kind of requests.
If you want to stick with the standard product I can see a workaround but this is a bit of a "dirty" one.
You can misuse (abuse) the Name attribute of the Person entity by adding a business rule to the Person entity that generates the content of the Name attribute as a concatenation of multiple attributes. You of course need an additional attribute that serves as a place holder for the original Name. The concatenated field will then show in your customer entity.
One question that does come to mind is why a user would like/need to see the gender of a person in a customer list? As you have a separate Person entity I expect you to have multiple persons per customers. What would the gender of one person - even if it is the main contact - matter?

Cannot use group with has_many through in Rails 5

I have the following associations:
class Student < ApplicationRecord
has_many :people_schools
has_many :schools, through: :people_schools
end
class PeopleSchool < ApplicationRecord
belongs_to :student
belongs_to :school
end
class School < ApplicationRecord
has_many :people_schools
has_many :students, through: :people_schools
end
I am trying to get a list of students organized by their school. I have tried the following:
Student.joins(:schools).all.group('schools.name')
but I get the following error:
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "students.id" must appear in the GROUP BY clause or be used in an aggregate function
How do I fix this?
When the association fires, it will generate a SQL query like
SELECT students.id, students. ...
FROM students
JOIN schools
ON ...
GROUP BY schools.name
In sql when grouping, a projection (SELECT) can only include columns that are grouped by or aggregations (e.g. MAX, MIN) of columns (regardless of whether they are grouped by). Therefore adding something like the following would turn it into a valid sql:
# column that is grouped by
Student.joins(:schools).group('schools.name').select('schools.name')
# aggregate function
Student.joins(:schools).group('schools.name').select('schools.name, COUNT(students.id)')
But how you want to fix it in your case depends on what you want to get out of the query.
In answer to the comment
Assuming a student is only member of a single school, which requires changing the association to a belongs_to :school (without the join table) or a has_one :school (with join table).
Student.includes(:school).group_by(&:school)
This will issue an SQL statement to get all students and their school (eager loaded for optimization). Only after the models (Student, School) are instantiated ruby objects, is the group_by method evaluated, which will return a Hash where the school is the key referencing an Array of students.

MongoDb conditional relationship

Suppose I have following 4 collections:
1- posts
2- companies
3- groups
4- users
Bellow is my current structure in post:
and their relation is:
A company has an owner and many other members (user collection).
A group has many members (users).
A user has many posts.
A group has many posts that published by one of its members.
A company has many posts that published by its owner or members.
Now i have a problem on storing relation of users, company, and group with posts collection.
Bellow is my current structure:
I have decided to have a field postable inside my post document, and has a type field that will be 'user', or 'group', or 'company', and two other fields name, and id that will be company/group id and company/group name in cases that post is belonged to company or group but not user means type="group" || type="company".
Now how i can handle this to map id as FK of group and company collection (one field FK of two collection) ?
Is it the right structure ?
What you have here is a polymorphic association. In relational databases, it is commonly implemented with two fields, postable_id and postable_type. The type column defines which table to query and id column determines the record.
You can do the same in mongodb (in fact, that is what you came up with, minus the naming convention). But mongodb has a special field type precisely for this type of situations: DBRef. Basically, it's an upgraded id field. It carries not only the id, but also collection name (and database name).
how i can handle this to map id as FK of group and company collection (one field FK of two collection)?
Considering that mongodb doesn't have joins and you have to load all references manually, I don't see how this is any different from a regular FK field. Just the collection name is stored in the type field now, instead of being hardcoded.

How can I implement a dynamic checklist with additional comments using MongoDB and rails?

I am building a project that involved car servicing. I have an admin panel which allows the creation of services, and each service has a number of checks to perform (The checks themselves and belong to multiple services). The solution looks like this:
class Service
include Mongoid::Document
field :name, type: String
field :price, type: Integer
has_and_belongs_to_many :checks
end
class Check
include Mongoid::Document
field :name, type: String
has_and_belongs_to_many :services
end
These checks are performed on an instance 'Appointment'. So when an appointment is carried out, all the necessary checks are displayed (depending on the type of service).
What is the best way to create and store an instance of these checks?
In mySQL, I would create an appointment_check table with appointment_id and check_id as a compound key, and have the details of the check in there.
Is this the best way to resolve this in MongoDB? But surely this involves a join..
Is there a solution I'm missing?
Thanks
MongoDB does not know the concept of joins. So in your case you would not have a appointment_check table, as the has_and_belongs_to_many are just arrays of ids, in both sides.
What I would do in your case, is to have a belongs_to :appointment in the Check model, so you can have a appointment_id and the check_id within the same document.

Combining postgres_ext (or Rails 4) arrays with associations

I'm trying to develop a many-to-many relationship between tags (in the tags table) and items (in the items table) using a field of type integer[] on each item.
I know that Rails 4 (and Rails 3 via postgres_ext) has support for Postgres' arrays feature through the :array => true parameter, but I can't figure out how to combine them with Active Record associations.
Does has_many have an option for this? Is there a gem for this? Should I give up and just create a has_many :through relationship (though with the amount of relations I'm expecting this is probably unmanageable)?
At this point, there isn't a way to use relationships with arrays in Rails. Using the selected answer though, you will run into the N+1 select issue. Say you get your posts and then the tags for it on each post with "tags" method defined in the class. For each post you call the tags on, you will incur another database hit.
Hopefully, this will change in the future and we can get rid of the join table (especially given that Postgres 9.4 will include support for foreign keys in Arrays).
All you really need to do is
def tags
Tag.where(id: tag_ids)
end
def add_tag(tag)
self.tag_ids += [tag.id] unless tag_ids.include?(tag.id)
end
At least that's what I do at the moment. I do some pretty cool stuff with hashes (hstore) as well with permissions. One way of handling tags is to create the has_many through and persist the tags in a string array column as they are added for convenience and performance (not having to query the 2 related tables just to get the names out). I you don't necessarily have to use active record to do cool stuff with the database.