Reputation: 19979
I have an Item which I split the table with cache_item. CachItem contains some serialized fragments. Like this:
class Item < ActiveRecord::Base
has_one :cache_item
end
class CacheItem < ActiveRecord::Base
belongs_to :item
end
how would I tell it to create one and save it automatically?
I do something like this:
if !cache_item
CacheItem.create! item_id: id
self.reload # seems like I shouldn't have to do this
end
but seems like there should be a single call. Is there?
For a has_many, I can do:
>item.comments.count
>1
>item.comments.create! # inserts with proper information
>2
What is the pattern for a has_one?
Upvotes: 1
Views: 1292
Reputation: 90
For an Item that has_many Comment(s) you use:
Item.comments.create()
And for an Item that has_one Comment you use:
Item.create_comment
Upvotes: 1
Reputation: 9288
For a has_one
association, you can use create_association!
as documented: http://guides.rubyonrails.org/association_basics.html#has-one-association-reference
In your case
item.create_cached_item!
Upvotes: 2