mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 23:58:01 +00:00
Add Creating Records of Has_One Associations as a rails til.
This commit is contained in:
@@ -24,6 +24,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
### rails
|
### rails
|
||||||
|
|
||||||
- [Attribute Was](rails/attribute-was.md)
|
- [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)
|
- [Show Pending Migrations](rails/show-pending-migrations.md)
|
||||||
|
|
||||||
### ruby
|
### ruby
|
||||||
|
|||||||
27
rails/creating-records-of-has-one-associations.md
Normal file
27
rails/creating-records-of-has-one-associations.md
Normal 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...>
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user