多个模型有多个

时间:2018-08-15 17:56:15

标签: ruby-on-rails rails-activerecord model-associations

我有一个带有嵌套模型参与者的模型事件。每个与会者可以是3个角色之一(:guide,:marshal和:organizer)。

class Event < ApplicationRecord

  has_many :attendees, dependent: :destroy
  has_many :guides, -> { Attendee.guide }
  has_many :marshals, -> { Attendee.marshal }
  has_many :organizers, -> { Attendee.organizer }
end

_

class Attendee < ApplicationRecord

  belongs_to :event

  validates :name, presence: true
  validates :role, presence: true
  validates :email, email: true

  enum role: %i[guide marshal organizer]

  scope :guide, -> { where(role: :guide) }
  scope :marshal, -> { where(role: :marshal) }
  scope :organizer, -> { where(role: :organizer) }
end

我希望我的事件注册表单具有每种角色类型的嵌套表单。我正在尝试这样的事情。

<%= 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 %>

提交后,我收到以下错误消息。

uninitialized constant Event::Guide

关于如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:1)

您的事件模型需要看起来像这样:

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

额外的关联需要知道他们正在链接的模型-如错误所示,他们目前正在猜测例如guides与某些名为Guide的模型相关联。

(您也不需要在与会者中使用这些scope,我认为...我相信enum会自动为您定义相同的那些。)

答案 1 :(得分:0)

我仍然会走一条完全不同的道路来创建更好的域模型:

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

您为与会者建模的方式被锁定为单个角色。而是创建作用域为事件的角色。