1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Creating Records of Has_One Associations as a rails til.

This commit is contained in:
jbranchaud
2015-03-19 22:25:22 -05:00
parent 8a366d5275
commit 5729c4ed48
2 changed files with 28 additions and 0 deletions

View File

@@ -24,6 +24,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
### rails
- [Attribute Was](rails/attribute-was.md)
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
- [Show Pending Migrations](rails/show-pending-migrations.md)
### ruby

View File

@@ -0,0 +1,27 @@
# Creating Records of Has_One Associations
When working with a model, say a User, that has a `has_many` association
with another model, say a Post, you can create a new post for a user like
so:
```ruby
u1 = User.first
=> #<User:0x...>
u1.posts.create(title: "Some Title", content: "...")
=> #<Post:0x...>
```
What about with a `has_one` association? Consider a Customer that has a
`has_one` association with an Account. Rails provides this method for you:
```ruby
c1.create_account(account_number: 123, ...)
=> #<Account:0x...>
```
Rails also gives you a similar `build` method:
```ruby
c1.build_account(account_number: 123, ...)
=> #<Account:0x...>
```