Ruby on rails “多个”对同一模型具有多个属性
我有一个嵌套模型与会者的模型事件。每个与会者可以是3个角色中的1个(:向导、:封送员和:组织者)Ruby on rails “多个”对同一模型具有多个属性,ruby-on-rails,rails-activerecord,model-associations,Ruby On Rails,Rails Activerecord,Model Associations,我有一个嵌套模型与会者的模型事件。每个与会者可以是3个角色中的1个(:向导、:封送员和:组织者) 类事件{Attendee.guide} 有很多:封送员,>{Attendee.marshal} 有很多:组织者,->{Attendee.organizer} 结束 _ 课堂参与者{where(role::guide)} 作用域:封送,->{where(role::marshal)} 作用域:组织者,->{其中(角色::组织者)} 结束 我希望我的事件注册表单为每个角色类型都有嵌套表单。我正在尝试
类事件{Attendee.guide}
有很多:封送员,>{Attendee.marshal}
有很多:组织者,->{Attendee.organizer}
结束
_
课堂参与者{where(role::guide)}
作用域:封送,->{where(role::marshal)}
作用域:组织者,->{其中(角色::组织者)}
结束
我希望我的事件注册表单为每个角色类型都有嵌套表单。我正在尝试这样的东西
<%= form_for @event, url: event_create_path(@event.handle) do |f| %>
<%= f.fields_for :organizers do |f| %>
<%= render partial: "attendee_fields", locals: {f: f} %>
<% end %>
<%= f.fields_for :guides do |f| %>
<%= render partial: "attendee_fields", locals: {f: f} %>
<% end %>
<%= f.fields_for :marshals do |f| %>
<%= render partial: "attendee_fields", locals: {f: f} %>
<% end %>
<% end %>
提交时,我收到以下错误
未初始化常量事件::指南
关于如何解决这个问题,您有什么想法吗?您的事件模型需要看起来更像这样:
class Event < ApplicationRecord
has_many :attendees, dependent: :destroy
has_many :guides, -> { guide }, class_name: "Attendee"
has_many :marshals, -> { marshal }, class_name: "Attendee"
has_many :organizers, -> { organizer }, class_name: "Attendee"
end
类事件{guide},课程名称:“与会者”
有许多:马歇尔,->{marshall},班名:“与会者”
有许多:组织者,->{organizer},班名:“与会者”
结束
额外的关联需要知道他们链接的是哪个模型——正如错误所示,他们目前猜测例如guides
与名为Guide
的模型关联
(你也不应该在Attendee中需要那些
范围
,我不认为……我相信枚举
会自动为你定义相同的范围。)我仍然会走一条完全不同的道路来创建更好的域模型:
class Attendee
has_many :attendences
has_many :events, through: :attendences
end
class Attendance
enum role: %i[guide marshal organizer]
belongs_to :attendee
belongs_to :event
end
class Event
has_many :attendences
has_many :attendees, through: :attendences
Attendance.roles.each do |key,int|
has_many key, through: :attendences,
source: :attendee,
-> { where(Attendance.call(key)) }
end
end
您为与会者建模的方式锁定为单个角色。这将创建一个事件的作用域。这不应该是:
有很多:指南,->{Attendee.guide}
更像:作用域:指南,->{attendes.guide}
?(另外,我将与会者:guide
范围改为复数形式:guides
)我确实同意,对于类似活动的模型,这可能是更好的方式。我在示例中使用Event,因为它很容易理解。然而,我的实际用例略有不同,在这里,与会者除了父母之外,不会成为任何其他人的一部分。美丽!非常感谢。我唯一遗漏的另一件事是它的反向关系,允许它连接行走<代码>有很多:向导,->{guide},类名:“与会者”,与::walk相反
class Event < ApplicationRecord
has_many :attendees, dependent: :destroy
has_many :guides, -> { guide }, class_name: "Attendee"
has_many :marshals, -> { marshal }, class_name: "Attendee"
has_many :organizers, -> { organizer }, class_name: "Attendee"
end
class Attendee
has_many :attendences
has_many :events, through: :attendences
end
class Attendance
enum role: %i[guide marshal organizer]
belongs_to :attendee
belongs_to :event
end
class Event
has_many :attendences
has_many :attendees, through: :attendences
Attendance.roles.each do |key,int|
has_many key, through: :attendences,
source: :attendee,
-> { where(Attendance.call(key)) }
end
end