On Sat, Sep 24, 2016 at 12:01 PM, Richard McSharry <[email protected]>
wrote:
**Example 1 - one-to-one**
> ```ruby
> class Employee
> has_one :salary
> end
> class Salary
> has_key_for :employee
> end
> ```
>
Generally speaking, the Active Record API expresses stuff at the entity
level, at the model level.
For example, in idiomatic Active Record, if you have a user instance and
want to fetch their posts you do NOT write this thing (that I sometimes see
in the wild):
Post.where(user_id: user.id)
That is thinking in SQL. It is a direct translation of a SELECT. In Active
Record the whole API is oriented to entites, you write instead
user.posts
which is pleasant, isn't. It flows.
Make no mistake, AR is not supposed to be magical or a black box. Active
Record is a SQL generator, you gotta now what you are doing. As a
programmer you know the SELECTs you need, but at the same time the API is
such that you can express them that way: user.posts. Reads awesome, done.
`belongs_to` is the name of the macro because in many cases things belong
to their parents at the model level. In the canonical AR example, comments
belong to posts, like in real life, you know. Posts belong to authors or
users. Invoice lines belong, are part of, their invoices, a task belongs to
a to-do list, a wing belongs to an airplane, and so on.
On the other hand, has_key_for expresses at a different level, closer to
SQL, in general that's not the approach of AR. Of course, if the defaults
do not match the schema, then you configure options that start to get
closer to SQL, because you need to. But that's the exceptional stuff, the
one you support allowing the design to depart. You design the API to read
naturally thinking about models, and at the same time leave room for the
non-conventional needs going down in the vocabulary to SQL as needed.
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.