验证Rails中红宝石的多态关系

时间:2019-06-07 02:59:08

标签: ruby-on-rails ruby-on-rails-4

我实现了多态关系

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_eventlocation_event的数据相同,但不能为空,如何验证其数据?

def type_place_params
    params.require(:place_event).permit(:name, :address, :phone_number, :web_site, :latitude, :longitude)
  end

0 个答案:

没有答案