Associations between classes
Association rails, associations in rails is sometimes a hard concept to wrap peoples head around but I’ll try to simplify.
Let us imagine we are building a pizza delivery application where our user class carries the users name and address and where pizza has different variation of pizzas. We create our models by running
rails g model pizza pizza:
rails g model user name: address:
Then the next step is to make a single source of truth.
Currently our models have no relation. However now when we create our joiner class, which will be Order class. Our order has to know our pizzas and users, so we generate a model
rails g model Order user:references pizza:references
when we create our attributes with references, rails does a bit of its magic and allows us to access information from different classes now let’s say we wanted to create a list of all the user is associated with we will be able to access @instance_variable.pizzas. we would be able to because we have not created our relationships.
So now we create the relation between the single source of truth and the the other class. which involves us having to go into the models and explicitly state the relation between models.
class Pizza
has_many :orders
has_many :users, through: :orders
end
class Order
belongs_to :pizza
belongs_to :user
end
class User
has_many :orders
has_many :pizzas, through: :orders
end
Make sure that when you create the relations that the other models are associated plural and now users will be able to get information that isn't from the user original class.