如何与 Rails 中的现有记录创建多对一关系
我正在尝试实现类似于下面的内容。基本设置是 Schedule
模型,
class Schedule < ActiveRecord::Base
has_many :events
end
然后 Event
模型将属于 Schedule
。 事件由名称、日期时间、运行时长和房间
组成。
房间
是在创建事件时从选择列表中选择的,所有房间都是通过播种或预先创建的。管理界面。房间将存储座位数等信息。
我一直在努力寻找一种感觉正确的方法来实现这一点。解决方案似乎介于 habtm 或 has_many :through 之间,但我看不出这种情况需要连接表。 理论上,一个事件 has_one :room
但反向关系不是 belongs_to :event
因为 Room 可以用于许多事件,这也需要外键打开房间的桌子。
我考虑过在模型中使用 room_id 外键在事件中手动处理此问题,然后我可以查询相关的 Room。我认为这会起作用,因为我目前无法看到使用房间查找所有事件的要求。
class Event < ActiveRecord::Base
belongs_to :schedule
def room
Room.find(room_id)
end
end
到目前为止,我在 Rails 中所做的一切都感觉“正确”,但我在这里提出的所有解决方案却并非如此,我觉得我错过了一些东西;或者也许我只是期待额外的魔力。 有没有一种“Rails”方法可以做到这一点?
I'm trying to implement something similar to that below. Basic setup is a Schedule
model
class Schedule < ActiveRecord::Base
has_many :events
end
The Event
model will then belong_to a Schedule
.
Events are comprised of a name, datetime, running length and a Room
A Room
is chosen from a select list when the event is created, all Rooms are created beforehand through seeding or admin interface. Room will store information like seating count.
I've been trying to find a method implementing this that feels right. Solutions seem to range between habtm or has_many :through but I can't see the need for a join table for this situation.
Theoretically, an Event has_one :room
but the reverse relationship isn't belongs_to :event
as a Room may be used for many events, this also requires the foreign key to be on the rooms table.
I've considered handling this manually in the model using a room_id foreign key in the event, I could then query for the relevant Room. I think this would work since I currently cannot see a requirement for finding all events using a Room.
class Event < ActiveRecord::Base
belongs_to :schedule
def room
Room.find(room_id)
end
end
Everything I've done so far in Rails has felt 'right', but all the solutions I've come up with here doesn't and I feel like I'm missing something; or maybe I'm just expecting that extra bit of magic.
Is there a "Rails" way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,Event 是否只与 Room 具有belongs_to 关系?
如果您从模式角度考虑,您的“事件”表几乎肯定有“schedule_id”和“room_id”列。
关系的另一面是一个 Room has_many Events。
Wouldn't Event just have a belongs_to relationship to Room in this case?
If you think about it from a schema perspective, your "events" table almost certainly has "schedule_id" and "room_id" columns.
The other side of the relationship is that a Room has_many Events.