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

十年热恋 提交于 2021-02-07 18:32:36

问题


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]

回答1:


Rails needs to be made aware how the belongs_to and has_many relate to each other. You are filling the has_many and testing for the belongs_to so you have to "explain" to rails those associations are inverses of each other :)

So in your case this should do the trick:

class Room < ActiveRecord::Base
  has_many :students, :inverse_of => :room
  accepts_nested_attributes_for :students
end

class Student < ActiveRecord::Base
  belongs_to :room, :inverse_of => :students
  validates_presence_of :room
end 


来源:https://stackoverflow.com/questions/29851203/activeadmin-has-many-form-not-saved-if-parent-model-is-new-and-is-not-null-in-ch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!