samedi 25 avril 2015

ActiveAdmin has_many form not saved if parent model is new and is NOT NULL in child model


I have two models, Room and Student. Room has_many Students. Student belongs_to Room.

I got an error Room can't be blank when I try to add Student to Room during creating a new Room.

My guess is that, upon submission, child object (student) is saved before parent object (room) is saved. Is there a way to bypass the order without remove the NOT NULL setting on room_id? Or my guess is wrong? Or even worse, I am doing it wrong?

# app/models/room.rb
class Room < ActiveRecord::Base
  validates :name, presence: true
  has_many :students

  accepts_nested_attributes_for :students
end



# app/models/student.rb
class Student < ActiveRecord::Base
  validates :name, presence: true

  belongs_to :room
  validates :room, presence: true # room_id is set to NOT NULL in database too.

end



# app/admin/room.rb
  form do |f|
    f.semantic_errors *f.object.errors.keys
    f.inputs "Room Details" do
      f.input :name

      f.has_many :students do |student|
        student.input :name
      end
    end

    f.actions
  end

  permit_params :name, students_attributes: [:name]


Aucun commentaire:

Enregistrer un commentaire