问题
I have two models, Room
and Student
.
Room
has_many
Student
s.
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