Rails 在循环中创建嵌套字段

Rails nested fields creation in loop

我有三个模型class彼此相关。

 class Student < ActiveRecord::Base

  has_many :marks
  belongs_to :group

  accepts_nested_attributes_for :marks,
                                reject_if: proc { |attributes| attributes['rate'].blank?},
                                allow_destroy: true

end

这个 class 描述了一个有很多分数的学生,我想创建一个学生记录和他的分数。

 class Mark < ActiveRecord::Base

  belongs_to :student, dependent: :destroy
  belongs_to :subject

end

分数与学科和学生都相关。

class Subject < ActiveRecord::Base

  belongs_to :group
  has_many :marks

end

当我尝试在循环中创建标记的嵌套字段并用主题名称标记它们并通过循环将其传入 subject_id 时出现问题 - 只有最后一个标记的嵌套字段被正确保存,而忽略其他字段。这是我的表单视图代码:

 <%= form_for([@group, @student]) do |f| %>
        <%= f.text_field :student_name %>
        <%=f.label 'Student`s name'%><br>
        <%= f.text_field :student_surname %>
        <%=f.label 'Student`s surname'%><br>
        <%=f.check_box :is_payer%>
        <%=f.label 'Payer'%>
        <%= f.fields_for :marks, @student.marks  do |ff|%>
            <%@group.subjects.each do |subject| %><br>
                <%=ff.label subject.subject_full_name%><br>
                <%=ff.text_field :rate %>
                <%=ff.hidden_field :subject_id, :value => subject.id%><br>
            <%end%>
        <% end %>
        <%= f.submit 'Add student'%>
    <% end %>

这是我的控制器代码:

class StudentsController<ApplicationController

  before_action :authenticate_admin!

  def new
    @student = Student.new
    @student.marks.build
    @group = Group.find(params[:group_id])
    @group.student_sort
  end

  def create
    @group = Group.find(params[:group_id])
    @student = @group.students.new(student_params)
    if @student.save
      redirect_to new_group_student_path
      flash[:notice] = 'Студента успішно додано!'
    else
      redirect_to new_group_student_path
      flash[:alert] = 'При створенні були деякі помилки!'
    end
  end


  private
  def student_params
    params.require(:student).permit(:student_name, :student_surname, :is_payer, marks_attributes: [:id, :rate, :subject_id, :_destroy])
  end
end

我该如何解决?

@student.marks.build

此行将保留一个对象标记。

如果你想要多标记,可能你在新动作中需要这样的东西:

@group.subjects.each do |subject|
   @student.marks.build(:subject=> subject)
end

希望对你有用。