导轨如何创建具有多态关联的新纪录?

问题描述 投票:0回答:1

我有一个Location模型,该模型通过:locatable多态性

一个EventLocation

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。我怎样才能为事件创建一个位置?

谢谢

ruby-on-rails activerecord ruby-on-rails-5
1个回答
1
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.