tôi có các mô hình sauLàm thế nào để xử lý nhiều mô hình trong một hình thức đường ray?
class Survey < ActiveRecord::Base
has_many :survey_sections
accepts_nested_attributes_for :survey_sections
end
class SurveySection < ActiveRecord::Base
belongs_to :survey
has_many :questions
accepts_nested_attributes_for :questions
end
class Question < ActiveRecord::Base
belongs_to :survey_section
has_many :answers
belongs_to :question_group
accepts_nested_attributes_for :question_group
accepts_nested_attributes_for :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
end
class QuestionGroup < ActiveRecord::Base
has_many :questions
end
điều khiển của tôi:
def new
@survey = Survey.new
survey_section = @survey.survey_sections.build
survey_section.questions.build
end
def create
@survey = Survey.new(survey_params)
if @survey.save
redirect_to @survey, notice: 'Super'
else
render 'new'
end
end
def survey_params
params.require(:survey).permit(:title, :description, survey_sections_attributes:[:id, :title, questions_attributes:[:id, :text, answers_attributes:[:id, :text]]])
end
Làm thế nào chúng ta có thể lưu dữ liệu trong hơn sau đó 3 mô hình? Hiện tại tôi có thể lưu dữ liệu biểu mẫu khảo sát của tôi vào khảo sát, phần khảo sát và mô hình câu hỏi. Nhưng tôi không biết những gì tôi có trong bộ điều khiển mà tôi có thể lưu dữ liệu vào các mô hình khác.
Đề xuất của tôi là tránh sử dụng nested_forms. Nó được gọi là đường ray, nhưng nó làm tăng sự phức tạp và khớp nối rất nhiều. Tốt hơn là tạo biểu mẫu với một chút nỗ lực hơn một cách thủ công và sử dụng đối tượng Form để xử lý nó. Bạn có thể google cách tiếp cận này. – vladra