https://github.com/williamcunningham/delegatedtypes
This is a learning depository -- Rails' ActiveRecord::DelegatedType design pattern.
https://github.com/williamcunningham/delegatedtypes
learn-to-code rails7 ruby
Last synced: 5 months ago
JSON representation
This is a learning depository -- Rails' ActiveRecord::DelegatedType design pattern.
- Host: GitHub
- URL: https://github.com/williamcunningham/delegatedtypes
- Owner: WilliamCunningham
- Created: 2023-09-05T18:29:49.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2023-09-08T19:41:10.000Z (almost 3 years ago)
- Last Synced: 2025-04-07T08:45:22.139Z (over 1 year ago)
- Topics: learn-to-code, rails7, ruby
- Language: Ruby
- Homepage:
- Size: 49.8 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# README
This README file is my definition of Rails ActiveRecord::DelegatedType.
Rails provides different methods to create class relationships or associations including belongs_to, has_one, has_many, has_many :through, and has_and_belongs_to_many. In addition, Rails includes Polymorphic associations, Self Joins, Single Table Inheritance, and Delegated Types.
**Polymorphic Associations** allows a model to belong to (belongs_to) multiple models through a polymorphic join (classable_id and classable_type) fields rather than through the primary id. An example is having a Image class belongs to Employee, Product and Blog classes. This allows you to retrieve images for Employee (@user.images) or Product (@product.images).
**accepts_nested_attributes_for** is available for **delegated_type** associations (see this [PR](https://github.com/rails/rails/pull/41717)) This replaces writing specific methods like:
```
class Entry < ApplicationRecord
delegated_type :entryable, types: %w[ Message Comment ]
def self.create_with_comment(content, creator: Current.user)
create! entryable: Comment.new(content: content), creator: creator
end
end
```
with:
```
class Entry < ApplicationRecord
delegated_type :entryable, types: %w[ Message Comment ]
accepts_nested_attributes_for :entryable
end
params = { entry: { entryable_type: 'Comment', entryable_attributes: { content: 'Smiling' } } }
entry = Entry.create(params[:entry])
```