我实现了多态关系
class PlaceEvent < ActiveRecord::Base
belongs_to :event_place, polymorphic: true
end
class LocationEvent < ActiveRecord::Base
has_many :place_events, as: :event_place
end
class PrecintEvent < ActiveRecord::Base
has_many :place_events, as: :event_place
end
在这里,我保留多态关系的数据
def create
if params[:place_event][:type_place] == PrecintEvent.name
type_place = PrecintEvent.new(type_place_params)
elsif params[:place_event][:type_place] == LocationEvent.name
type_place = LocationEvent.new(type_place_params)
end
@place_event = PlaceEvent.new(place_event_params)
@place_event.event_place = type_place
if @place_event.save
render json: {status: 'created', message: 'Place Event save'}
else
render json: @place_event.errors, status: :unprocessable_entity
end
end
precint_event
和location_event
的数据相同,但不能为空,如何验证其数据?
def type_place_params
params.require(:place_event).permit(:name, :address, :phone_number, :web_site, :latitude, :longitude)
end