My situation is this: I have two models, Model
(as in car model) and Engine
. I have some Models
which have more than one Engine
(different model years came with different engines), and I have some Engines
which belong to multiple different Models
(single engine was reused across multiple models).
Forgive me for being (very) new to Rails and ActiveRecord, but this seems a bit more complicated than just a has_many
and belongs_to
. I could be wrong. I should also note that I'm using Rails 5
.
Given that I already have my scaffolds/models in place and I'd rather not delete them, how do I write a migration to achieve the above situation? What do I need to add to the respective models?
Use many-to-many relationship, make sure your migration name contains JoinTable
rails g migration CreateEngineModelJoinTable engines models
Engine class
class Engine < ActiveRecord::Base
has_and_belongs_to_many :models
end
Model class
class Model < ActiveRecord::Base
has_and_belongs_to_many :engines
end
You can access it by
engines = model.engines
models = engine.models
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments