我有两个模型,Room
和Student
。
Room
has_many
Student
s。
Student
belongs_to
Room
。
我在创建新房间时尝试将学生添加到房间时出现错误房间不能为空。
我的猜测是,提交后,在保存父对象(房间)之前保存子对象(学生)。有没有办法绕过订单而不删除room_id上的NOT NULL设置?或者我的猜测是错的?或者更糟糕的是,我做错了?
# 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]
答案 0 :(得分:3)
需要让Rails知道belongs_to
和has_many
之间的关系。您正在填写has_many
并测试belongs_to
,因此您必须向rails解释这些关联是彼此的反转:)
所以在你的情况下,这应该可以解决问题:
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