1

I have a Location model that is polymorphic via :locatable

An Event has a Location:

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

In the events_controller#create, how can I create a new Event with the location passed in via params?

def create
  property = Event.create! params.require(:event).permit(:name, :time, :location, :organizer_id, attachments: [])
  # ... other stuff, and finally render JSON response
  end

However, Event.location is nil. How can I create a location for the Event?

Thanks

a person
  • 1,518
  • 3
  • 17
  • 26
  • Do you want to create a new location or just associate existing location with a new event? – Vasilisa Feb 04 '19 at 03:33
  • Show your server's log when you do that request. `:location` on the permitted hash references a single value, check this question too https://stackoverflow.com/questions/3969025/accepts-nested-attributes-for-with-belongs-to-polymorphic – arieljuod Feb 04 '19 at 04:05

1 Answers1

1

locations table contains a foreign key called locatable_id, which establish polymorphic association to the events table.

To create a location belonging to a 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
Anand
  • 6,457
  • 3
  • 12
  • 26
  • It is better to use `accepts_nested_attributes_for`, if author needs to create a new location together with event – Vasilisa Feb 04 '19 at 08:53
  • @Vasilisa Yep, that can be an alternative too . thanks :) – Anand Feb 04 '19 at 18:09
  • can you give me an example for that? I tried it by adding `accepts_nested_attributes_for :location` to my Event model. In the controller, i per mit `location_attributes: [:street_1, ..etc ]` but location is not created. – a person Feb 08 '19 at 04:05
  • @aperson Here is an example https://stackoverflow.com/questions/3969025/accepts-nested-attributes-for-with-belongs-to-polymorphic – Anand Feb 08 '19 at 04:51
  • @aperson Also you can look here https://github.com/activeadmin/activeadmin/wiki/Nested-forms-with-polymorphic-association-in-Active-Admin-Formtastic – Anand Feb 08 '19 at 04:52
  • @aperson Here https://forum.upcase.com/t/rails-polymorphic-associations-in-a-nested-form-in-one-html-table/6708 – Anand Feb 08 '19 at 04:52