我有一个Location
模型,该模型通过:locatable
多态性
一个Event
有Location
:
class Event < ApplicationRecord
has_one :location, as: :locatable
end
在events_controller#create
,我怎么可以创建通过PARAMS传递的位置的新事件?
def create
property = Event.create! params.require(:event).permit(:name, :time, :location, :organizer_id, attachments: [])
# ... other stuff, and finally render JSON response
end
然而,Event.location是nil
。我怎样才能为事件创建一个位置?
谢谢
locations
表包含一个外键称为locatable_id
,其建立的多态关联到events
表。
要创建属于location
一个event
:
events_controller.rb
def create
event = Event.new(event_params)
location = event.location.build() #or event.location.build(location_parms)
location.save #will create record in events as well as location associated with the event
end
private
def event_params
#Whitelist only events attributes
params.require(:event).permit(:name, :time, :organizer_id, attachments: [])
end