我正在尝试为rails应用创建数据模型。
基本上我有一个位置表,其中包含四个不同位置的记录。我正在尝试为每个地点创建每个时间点的时间段。例如。 Location1有5个9am插槽,5个11am插槽等。
我现在需要能够为给定时间段创建位置安排。
目前我有这个应用程序工作,唯一的问题是,当您保存安排时,您还必须使用排列ID更新时间段记录,并且每天每个位置的每个时间段也必须存在记录。
我知道必须有更好的方法来做到这一点。
这是我当前的数据模型:
这是我目前的模型设置:
class Location < ActiveRecord::Base
has_one :arrangement
has_many :timeslots
end
class Timeslot < ActiveRecord::Base
belongs_to :location
has_one :arrangement
end
class Arrangement < ActiveRecord::Base
belongs_to :location
belongs_to :timeslot
end
这是我在排列控制器中当前创建方法的片段:
if @arrangement.save
# update the timslot record with the arrangement id
if @timeslot = Timeslot.update(@arrangement.timeslot_id, :arrangement_id => @arrangement.id)
如何让这个数据模型更好?
修改 理想情况下,我正在寻找一个数据模型,我不需要为每个位置和每天填充时间段。
理论上我想要一个只有每个位置的所有时隙的时隙表,这样我就不必手动填充时隙表了。
我担心的最重要的事情就是不得不填写时间表,让我们说接下来的30年。
答案 0 :(得分:0)
由于您打算为每个位置生成一些时隙,因此这将部分起作用:
class Location < ActiveRecord::Base
has_many :timeslots
has_many :arrangements, :through => :timeslots
end
class Timeslot < ActiveRecord::Base
belongs_to :location
has_one :arrangement
end
class Arrangement < ActiveRecord::Base
belongs_to :timeslot
end
设置此问题的一个问题是,由于您无法建立normally
关系,因此您无法belongs_to through
获取布置位置。
但你基本上可以执行arrangement.timeslot.user
,而不是与location
建立belongs_to关系,这有点多余,但你也可以这样做。
您无需在关系的has_one末端设置id:
http://guides.rubyonrails.org/association_basics.html#the-has_one-association
答案 1 :(得分:0)
您确实需要Location
和Arrangement
之间的直接关联吗?我会考虑使用has_many :through
关联来组织它,如下所示:
class Location < ActiveRecord::Base
has_many :timeslots
has_many :arrangements, through: :timeslots
end
class Timeslot < ActiveRecord::Base
belongs_to :location
has_one :arrangement
end
class Arrangement < ActiveRecord::Base
belongs_to :timeslot
end
如果您这样做,则会创建属于Arrangement
的{{1}},因此您无需手动更新。如果您想获得Timeslot
的所有Arrangement
,您仍然可以使用Location
执行此操作,因为您通过时间段设置了关联。如果您需要知道某个安排的位置,可以使用location.arrangements
。
(注意,我假设每个arrangement.timeslot.location
实际上可能有多个Location
,而你问题中的Arrangement
是错误的?让我知道我是不是在那方面是错误的。)