I’m working on a Dungeons and Dragons character database application. I’ve got a Character model and several models that belong to Character with a has_one association, such as HitPoints, ArmorClass and so on. These are all built, edited and displayed from the Character view. However, I want to create new pages with more information that belongs to the Character model. I want a link at the top of the view that takes the user to an Equipment page, with separate models displayed on that page, such as Weapons, Armor, Gear and so forth.
This is where I need some guidance. Would the Equipment page be a new model that belongs_to Character and I just load models for Weapon, Armor, Gear and so forth into the Equipment view?
If so, would these models have a belongs_to relationship with the Character model, the Equipment model or both?
Finally, if I build it this way: Character has_one Equipment and Equipment has_many Weapons, would the Weapons model also have a belongs_to relationship with the Character model?
Thanks in advance, I hope what I’m trying to do is clear. I’m still having trouble talking about what I want to accomplish with Rails.
It sounds like you’re misunderstanding some of the concepts around models. For example,
HitPointsandArmorClassshould not be models that have ahas_oneassociation with yourCharacter. They are just attributes ofCharacter. So your model should look something like this instead:Then you can access them like so:
Also, I’d say
Equipmentmodel is the wrong concept. What you need is anItemmodel. All of the things you mentioned (weapons, armor, gear) are all just items. And it makes a lot more sense that a “Character”has_many“Items”. Also that “Item”has_many“Characters” since you’ll presumably have multiple characters with multiple items…so it COULD be a many to many relationship to keep it simple. Then your “Item” model could have an “ItemType” field which tells you if it’s a weapon, armor, potion, etc.So your
Itemmodel could look like thisAnother option, which is closer to what you’re talking about is to add an
ItemSetmodel. We’d put this model betweenCharacterandItems. Doing it this way would let you sayhas_one“ItemSet”has_many“Items”So basically, this is showing that in your “world” you have many characters and items. But each character has a unique set of those items.
This is the way I’d do it.
In the code above you need to add the
has_many,has_one, etc attributes to the models. I left it out so you could see the models themselves a little easier and so you could figure out how you want to do it yourself.