【问题标题】:Rails how to create a new record which has a polymorphic association?Rails如何创建具有多态关联的新记录?
【发布时间】:2019-02-04 03:28:55
【问题描述】:

我有一个 Location 模型,它通过 :locatable 实现多态

一个Event 有一个Location

class Event < ApplicationRecord
  has_one :location, as: :locatable
end

events_controller#create 中,如何使用通过参数传入的位置创建一个新事件?

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。如何为活动创建地点?

谢谢

【问题讨论】:

  • 您想创建一个新位置还是只是将现有位置与新事件相关联?
  • 在您执行该请求时显示您的服务器日志。 :location 允许的哈希引用单个值,也检查这个问题 stackoverflow.com/questions/3969025/…

标签: ruby-on-rails activerecord ruby-on-rails-5


【解决方案1】:

locations 表包含一个名为locatable_id 的外键,它与events 表建立多态关联。

创建一个属于eventlocation

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

【讨论】:

  • 如果作者需要与事件一起创建新位置,最好使用accepts_nested_attributes_for
  • @Vasilisa 是的,这也可以作为替代方案。谢谢:)
  • 你能给我举个例子吗?我尝试将accepts_nested_attributes_for :location 添加到我的事件模型中。在控制器中,我允许 location_attributes: [:street_1, ..etc ] 但未创建位置。
  • @aperson 这是一个例子stackoverflow.com/questions/3969025/…
  • @aperson 你也可以看这里github.com/activeadmin/activeadmin/wiki/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多