在已建立的关联中建立多个关联

时间:2019-06-19 01:30:44

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

我需要建立多个关联,我有1个名为PrecintEvent的模型,并且该模型可以有许多FloorEvents,而每个FloorEvents可以有许多RoomEvents,需要保存所有这些关联

class PrecintEvent < ActiveRecord::Base
      has_many :floor_events
    end

class FloorEvent < ActiveRecord::Base
  belongs_to :precint_event
  has_many :room_events
end

class RoomEvent < ActiveRecord::Base
  belongs_to :floor_event
end

params[:alternate_precints]都是PrecintEvents

JSON.parse(params[:alternate_precints]).each do |precint|
    #I get all the floors of a PrecintEvent
    floors = Floor.where(precint_id: precint['id']).as_json

    precint = PrecintEvent.new(precint.except('id', '$$hashKey'))

    #Here I build all the FloorEvents of that PrecintEvent
    floors.each do |floor|
      #Here I get all the RoomEvents from 1 FloorEvent
      rooms = Room.where(floor_id: floor['id'])

      #Here I build the association but I need to save each RoomEvents 
      #to each FloorEvent
      precint.floor_events.build(name: floor['name'])
    end

    @event.alternate_place_events.build(event_place: precint)
  end

我该怎么做?

0 个答案:

没有答案
相关问题