在我的Rails應用程序中,我試圖爲TrainingClass
模型設置創建表單。我希望此表單允許用戶在同一表格中創建多個ClassMeeting
模型(與TrainingClass
模型具有belongs_to關係),並且我使用accepts_nested_attributes_for
來執行此操作。不幸的是,無論何時提交表單,我都會收到錯誤消息:Meetings class can't be blank
。在Rails中,如何使用accept_nested_attributes_for創建嵌套對象?
我意識到,這是因爲ClassMeeting
有validates :class_id, presence: true
,因爲TrainingClass
不能有一個ID,直到它被保存後,但我不知道以正確的方式來解決這個問題。 (我可以想到一些可能的方法,但它們並不完全是優雅的解決方案。)任何想法?我會很感激你能給我的任何幫助。
注意:我意識到過去有人問過類似這樣的幾個問題。然而,這些問題中的大部分都是陳舊的,並且已經過時了,他們都沒有解決我的問題。
這是我的代碼。請記住,雖然我已經簡化爲簡潔它的某些方面,ClassMeeting
和TrainingClass
模型之間的關係保持不變:
ClassMeeting型號:
# == Schema Information
#
# Table name: class_meetings
#
# id :integer not null, primary key
# class_id :integer
# start :datetime
# end :datetime
# location :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class ClassMeeting < ActiveRecord::Base
attr_accessible :start, :end, :location
validates :class_id, presence: true
validates :start, presence: true
validates :end, presence: true
validates :location, presence: true, length: {maximum: 255}
belongs_to :training_class, foreign_key: :class_id, inverse_of: :meetings
end
TrainingClass型號:
# == Schema Information
#
# Table name: training_classes
#
# id :integer not null, primary key
# description :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class TrainingClass < ActiveRecord::Base
attr_accessible :description, :meetings_attributes
validates :description, length: {maximum: 255}
has_many :meetings, class_name: :ClassMeeting, foreign_key: :class_id, inverse_of: :training_class
accepts_nested_attributes_for :meetings, allow_destroy: true
end
訓練類控制器:
class TrainingClassesController < ApplicationController
def new
@training_class = TrainingClass.new()
@training_class.meetings.build
end
def create
@training_class = TrainingClass.new()
if @training_class.update_attributes(params[:training_class])
redirect_to @training_class, notice: 'Class was successfully created.'
else
render "new"
end
end
end
TrainingClass表(視圖):
<%= form_for @training_class do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_area :description %>
<h2>Schedule</h2>
<%= f.fields_for :meetings do |meeting| %>
<%= meeting.label :start, "Start of Meeting:" %>
<%= meeting.text_field :start %>
<%= meeting.label :end, "End of Meeting:" %>
<%= meeting.text_field :end %>
<%= meeting.label :location, "Location:" %>
<%= meeting.text_field :location %>
<% end %>
<%= f.submit class:"btn btn-large btn-primary" %>
<% end %>