How to display data from a linking table - ruby-on-rails

Good Day I am hoping you can help me, i am really new to all of this.
I have two models:
Contractor
has_many :employees
Employee
belongs_to :contractor
I then created a migration table which stores an id, employee_id and contractor_id.
This allows me to link the two tables if i am correct?
Now the contractor is logging into the system which is work 100%, i would like him to be able to create employees and be able to view only his employees (not all the employees in the database).
What would be the best solution to this?
Thanks in advance!

No, that is not correct. You have a one (Contractor) to many (Employee) relationship. So what you have instead is a column in your employees table that is called contractor_id. This way you can use
Contractor#employees
to find all of your Employees that belong to a certain Contractor (source)
Good luck.

Related

How to associate 3 different models in to a 2 model relationship

The gist of the matter is I want to know the best way to associate the below setup.
I have 2 customer models. Individual Customer & Corporate Customer.
I have another Vehicle model. Which I would like to maintain separately.
I would like to have a HMT model called VehicleOwner. Which now adds the r/ship of any of the two(2) customers as an owner & the vehicle.
The reason for this approach is an architecture design to allow the same vehicle to be migrated to other customers and not have every time a customer wants to add a vehicle; they keep adding a vehicle even if we have it.
My question is this?
How can I link in the Vehicle Owner. That the owner can either be an individual customer or a corporate customer.
Or is there another better way to map the two(2) customers with a vehicle.
Thanks
Perhaps you are looking for Polymorphic association in Rails, in your case it would be, VehicleOwner model should look like
belongs_to :customer, polymorphic: true
In IndividualCustomer and CorporateCustomer models
has_many :vehicle_owners, as: :customer
This is just an example of how to implement this, you can read more about in official Rails guides
https://guides.rubyonrails.org/association_basics.html#polymorphic-associations
Hope that helps!

Relationship query: A company has many employees

Lets say a relationship is described as:
A company has many employees
A company has many departments
A department has many employees
So, something like this;
Company -<< Departments >>- Employees
If department table has a basic structure of:
// Pseduocode
company_id // Foreign key
department_id // Primary key
[employees] // Array or collection of employees
If we go back to this phrase;
A Company has many employees
Does this mean that the employee table needs or requires a reference for the company_id too?
So, Employee would be:
employee_id
company_id // I'm not sure if this is requried or not
department_id
I'm intending to hopefully abstract this data into a contracts table in case of employees are freelancers/contracters, etc or have multiple employees.
But for now..
My question is:
Does my employee table require a reference to the company table, or is the company reference implied via the department table?
Many thanks
Question is: do you need a straight connection between Company and Employee? If you do, add it, if not then yes, the connection is implied through Department.
EDIT:
Technically, your Department table does not need a list of Employees. Each row of Employee table has a reference ID to Department, that's enough.
Check this out for more information.
The relationship is implied through the department, so you don't conceptually need it. Adding it, would be an example of denormalisation, and would allow inconsistencies to crop up. For example, you might have company_1 with department_1 and company_2. Now employee_1 might be linked to department_1 but company_2, because of some flaw/bug in the application code. There's no way to express this constraint as a SQL schema, so you'd have to go with more complicated stuff such as triggers, or application code checks etc.
However, sometimes you only need info about companies and employees, but not about departments. If it's really performance critical, doing the extra join with departments in order to find the company for an employee or the employees for a company might not cut it, so you'll just have to live with the denormalisation.
You probably do not need to link Company with Employee. The relation between Departement and Company already do the job. You may need it only if there are existing particular cases requiring this relationship.

Referencing attributes across multiple tables in Rails

Let me try and condense my question:
I want to display data from multiple tables in a particular view. I want to list every person I have in a "People" table, and append there job on an "Affiliations" table listed with their company from an "Employers" table. Affiliations should belongs_to People and Employers, and Employers and People have_many Affiliations. What would the migration and controller look like?
I'm not entirely sure if this is the same as what you're asking, but using has_many and belongs_to may be a better solution. Using these associations would allow an employee to have many employers and then simply get the most recent one.
Please feel free to correct me if this isn't what you are asking.

How to design/model a has many relationship that has a meaningful join table?

I wasn't able to put well into words (in Question title) what I'm trying to do, so in honor of the saying that an image is worth a thousand words; In a nutshell what I'm trying to do is..
Basically, what I have is A Teacher has many Appointments and A Student has many Appointments which roughly translates to:
I'm trying to stay away from using the has_and_belongs_to_many macro, because my appointments model has some meaning(operations), for instance it has a Boolean field: confirmed.
So, I was thinking about using the has_many :through macro, and perhaps using an "Appointable" join table model? What do you guys think?
The Scenario I'm trying to code is simple;
A Student requests an Appointment with a Teacher at certain Date/Time
If Teacher is available (and wants to give lesson at that Date/Time), She confirms the Appointment.
I hope you can tell me how would you approach this problem? Is my assumption of using the has_many :through macro correct?
Thank you!
Both teachers and students could inherit from a single class e.g. Person. Then create an association between Person and Appointments. This way you keep the architecture open so that if in the future you want to add 'Parents' then they could easily be integrated and may participate in appointments.
It may not be completely straightforward how you do the joins with the children classes (Students, Parents, Teachers). It may involve polymorphic relationships which I don't particularly like. You should though get away with a single join table.
In any case, you want to design so that your system can be extended. Some extra work early on will save you a lot of work later.

Confusion over the tables for has_one and has_many

In the Rails ActiveRecord Associations guide, I'm confused over why the tables for has_one and has_many are identical:
Example tables for has_many:
customers(id,name)
orders(id,customer_id,order_date)
Example tables for has_one:
these tables will, at the database level, also allow a supplier to have many accounts, but we just want one account per supplier
suppliers(id,name)
accounts(id,supplier_id,account_number) #Foreign Key to supplier here??
Shouldn't the tables for has_one be like this instead:
suppliers(id,name,account_id) #Foreign Key to account here
accounts(id,account_number)
Now because the account_id is in the suppliers table, a supplier can never have more than one account.
Is the example in the Rails Guide incorrect?
Or, does Rails use the has_many kind of approach but restricts the many part from happening?
If you think about this way -- they are all the same:
1 customer can have many orders, so each order record points back to customer.
1 supplier can have one account, and it is a special case of "has many", so it equally works with account pointing back to supplier.
and it is the same case with many-to-many, with junction table pointing back to the individual records... (if a student can take many classes, and one class can have many students, then the enrollment table points back to the student and class records).
as to why account points back to supplier vs account points to supplier, that one I am not entirely sure whether we can have it either way, or one form is better than the other.
I believe it has to do with the constraints. With has_one rails will try to enforce that there is only one account per supplier. However, with a has_many, there will be no constraint enforced, so a supplier with has_many would be allowed to exist with multiple accounts.
It does take some getting used to when thinking about the relationships and their creation in rails. If you want to enforce foreign keys on the database side (since rails doesn't do this outside of the application layer), take a look at Mathew Higgins' foreigner
If I understand your question correctly, you believe there is a 1:1 relationship bi-directionally in a has_one/belongs_to relationship. That's not exactly true. You could have:
Class Account
belongs_to :supplier
belongs_to :wholesaler
belongs_to :shipper
# ...
end
account = supplier.account # Get supplier's account
wholesaler = Wholesaler.new
wholesaler.accounts << account # Tell wholesaler this is one of their suppliers
wholesaler.save
I'm not saying your app actually behaves this way, but you can see how a table -- no, let's say a model -- that "belongs to" another model is not precluded from belonging to any number of models. Right? So the relationship is really infinity:1.
I should add that has_one is really a degenerate case of has_many and just adds syntactic sugar of singularizing the association and a few other nits. Otherwise, it's pretty much the same thing and it's pretty much why they look alike.

Resources