Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve upon argument for using a one-to-one relationship #1278

Open
wgwz opened this issue Nov 20, 2023 · 0 comments
Open

Improve upon argument for using a one-to-one relationship #1278

wgwz opened this issue Nov 20, 2023 · 0 comments

Comments

@wgwz
Copy link

wgwz commented Nov 20, 2023

https://github.com/turingschool/curriculum/blob/master/source/topics/models/relationships.markdown#problem-scenario

Imagine we want to display a message like "Hello, John" in the header of each page. In our controller we would say Customer.find(17) and use @customer.first_name in our view. Rails will run a SQL statement like this:

SELECT * from CUSTOMERS where ID='17';

And, of course, that’s going to fetch the entire row from our customers table. We’re trying to get the first_name, so why bother fetching the birthday, gender, and home_city every request? Instead, we could create a one-to-one relationship between a customer and their "details".

The argument made assumes that you can only get ALL columns via SQL.
This is not true, as you can obviously select only particular columns.

SELECT first_name, birthday FROM CUSTOMERS where ID='17';

Stronger justification and reasons could be given.
I think a mention of something like the following might be helpful:

In a regular SQL query you can select just a particular column with SELECT first_name but because active record must always build a complete object, active record must always issue it's queries with SELECT *.

There might be some more verbiage that helps explain the scenario.
I'm just considering the perspective of developers like myself who are not new to SQL, but new to Rails/ActiveRecord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant