This is a simple Rails 7 project demonstrating the use of polymorphic relationships with Global ID for handling associations between three models: Person, Company, and Building. In this project, a Building can be associated with either a Person or a Company through polymorphism.
- Ruby 3
- Rails 7
- PostgreSQL (or any other supported database)
-
Clone the repository:
git clone https://github.com/italomatos/polymorphic-select.git
-
Navigate to the project directory:
cd polymorphic-select
-
Install dependencies:
bundle install
-
Set up the database:
rails db:create db:migrate
-
Run the server:
rails server
The application should now be running at
http://localhost:3000
.
Navigate to http://localhost:3000/people/new
and fill in the details to create a new person.
Navigate to http://localhost:3000/companies/new
and provide the necessary information to create a new company.
Navigate to http://localhost:3000/buildings/new
and choose either a person or a company to associate with the building.
Navigate to the details page of a building at http://localhost:3000/buildings/:id
, where :id
is the ID of the building. Here, you can see the associated person or company.
To change the association of a building, navigate to http://localhost:3000/buildings/:id/edit
and select a different person or company.
The key aspect of this project is the use of polymorphic relationships. This is achieved by defining the following associations in the models:
# app/models/building.rb
class Building < ApplicationRecord
belongs_to :onwer, polymorphic: true
def onwer_sgid=(value)
self.onwer = GlobalID::Locator.locate_signed(value)
end
end
# app/models/person.rb
class Person < ApplicationRecord
has_many :buildings, as: :owner
end
# app/models/company.rb
class Company < ApplicationRecord
has_many :buildings, as: :owner
end
This allows a Building to be associated with either a Person or a Company through the owner
association.
Feel free to contribute to this project by submitting issues or pull requests. Your feedback and contributions are highly appreciated!
This project is licensed under the MIT License - see the LICENSE.md file for details.