我在事件创建者背后的理论(和代码)方面遇到了一些麻烦。快速概述:
我有Customers
(用户),每个人都拥有Calendar
。一个Calendar
belongs_to
一个Customer
每个Calendar
has_many
Events
和Event belongs_to
一个Calendar
:
#customer.rb
class Customer < ActiveRecord::Base
belongs_to :business
has_one :calendar, :dependent => :destroy
...
end
#calendar.rb
class Calendar < ActiveRecord::Base
belongs_to :customer
has_many :events, :dependent => :destroy
end
#event.rb
class Event < ActiveRecord::Base
belongs_to :calendar
end
当客户在events\new.html.erb
中填写表单时,Events_controller的create
操作会从表单中获取信息,包括每个参与者客户的数组id_array
,该活动的创建者希望参与其中。
到目前为止,我已经做到这一点,以便events_controller遍历数组并为每个参与客户Event
创建一个相应的Calendar
:
def create
@calendar = current_customer.calendar
@newevent = @calendar.events.build(event_params) #creates event in creator's calendar
@participant_ids = params[:id_array]
@participant_ids.each do |item| #iterates through id array, finds corresponding customer and creates event
@participant = Customer.find(item)
@part_calendar = @participant.calendar
@part_event = @part_calendar.events.build(event_params) #adds event to participant's calendar
end
if @newevent.save
redirect_to '/main' #'/main/#{@calendar.id}'
else
redirect_to '/compose'
end
end
然而,这显然不令人满意,因为所创建的这些事件都不是彼此连接。我想知道最有效和最好的方法是让所有这些客户的日历分享事件(或共享一个唯一的标识符)。这样,如果创作者决定删除该活动,则会从所有参与的日历中删除该活动。
Here is also my event db migrate file for reference:
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.timestamps
t.references :calendar, foreign_key: true
t.string :name
t.string :description
t.date :day
t.datetime :starts_at
t.datetime :ends_at
t.string :location
end
end
end
答案 0 :(得分:1)
您可以自Event
引用:事件将包含许多事件并属于某个事件:
class Event < ActiveRecord::Base
has_many :events, dependent: :destroy
belongs_to :event, class_name: "Event"
end
您必须将event_id
作为integer
def create
@calendar = current_customer.calendar
@newevent = @calendar.events.build(event_params) #creates event in creator's calendar
if @newevent.save
# We wait until it's saved because we need its id
@participant_ids = params[:id_array]
@participant_ids.each do |item|
@participant = Customer.find(item)
@part_calendar = @participant.calendar
# We merge the newly created event id to the params
@part_event = @part_calendar.events.
build(event_params.merge(event_id: @newevent.id))
@part_event.save
end
redirect_to '/main' #'/main/#{@calendar.id}'
else
redirect_to '/compose'
end
end
这样你就有了这个:
我们假设customer
有一个日历,您可以通过表单创建event
并选择其他客户加入event
:
current_customer
将有新的event
,您选择的其他customer
中的每一个都会有一个新的event
(其中包含共享父event
这是event
的新current_customer
。这样:
event
将通过events
生成孩子event.events
。event
的{{1}},那么它的所有孩子current_customer
都将被销毁event
event
的父级活动