Complicated? Constructing a Model from other Models in Rails
I have created scaffolds for a number of resources in a rails application, and these form the content for the system.
What I need to do now is construct a form that lets a new user pick and choose the elements from the scaffolds, and then save this. In effect, it is a configuration of the other resources.
For example,
I have four models:
class House < ActiveRecord::Base
has_many :windows
has_many :doors
end
class Window < ActiveRecord::Base
belongs_to :house
has_many :locks
end
class Door < ActiveRecord::Base
belongs_to :house
has_many开发者_如何学运维 :locks
end
class Lock < ActiveRecord::Base
belongs_to :window
belongs_to :door
end
An administrator has uploaded all the available Windows, Doors and Locks into the system.
I need to build a new house that has a selection of these.I hope there is a simple way to do this but I can't think of a clean way unfortunately.
Do you mean you just want to have a 'house' saved where it is tied to certain combinations or windows, doors, and through them, locks?
If this is right, and if one house can have many windows and one window can be placed in many houses, you should consider changing your data model from has_many
to has_and_belongs_to_many
relationships.
This way, you can create multiple houses, each one of which: 1) has a combination of windows, 2) has a combination of doors, and 3) has a combination of locks.
If you are concerned about how to create the actual form, look into nested_form
.
https://github.com/ryanb/nested_form
http://blog.madebydna.com/all/code/2010/10/07/dynamic-nested-froms-with-the-nested-form-gem.html
The reason you are finding this difficult is because your relationships are not quite right. Using rooms as an example. You are using rooms as a lookup right? so you need a xref table to act as a many to many join between houses and rooms. You could call it something like house_room.You then create new house_room records for each room in the house that link between room and house. Your cross reference table In the case of rooms would need to have the foreign keys for house and room tables. You can then add as many windows as you like to the house_room but again this would need to be a room_window xref table that can have many locks.
Actually I think you will find polymorphic relationships useful to you for the locks. You don't need an xref table for those. A polymorphic relationship for locks will allow you to link a lock to different models.
DON'T be tempted to use has_and_belongs_to
Use has_many and has_many :through relationships.
You will find fields_for and accepts_nested_attributes combinations useful for building the forms and the view helper select function for choosing the window, lock etc... for each new xref record added.
That should give you plenty to think about and hopefully point you in the right direction to at least start thinking about what you need to know more about.
精彩评论