如果父模型是新模型并且在子模型

时间:2015-04-24 15:14:06

标签: ruby-on-rails activeadmin formtastic cocoon-gem

我有两个模型,RoomStudentRoom 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]

1 个答案:

答案 0 :(得分:3)

需要让Rails知道belongs_tohas_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