Rails在belongs_to关系中有很多

时间:2015-02-07 08:11:29

标签: ruby-on-rails ruby-on-rails-4 ruby-2.0

在我的rails应用中,我有以下型号

class Member < ActiveRecord::Base
  has_many :trainings
end

class Student < ActiveRecord::Base
  belongs_to :member
  has_many :trainings   #maybe a through relationship here
end

class Teacher < ActiveRecord::Base
  belongs_to :member
end

######编辑#################

class Training < ActiveRecord::Base
  belongs_to :member  #only member not student nor teacher
end

#############################

现在,我如何在学生控制器中构建培训

class StudentsController < ApplicationController
  def new
    @student = Student.new
    @student.trainings.build    #### This is not working
  end
end

由于

2 个答案:

答案 0 :(得分:0)

如果你使用的是rails 4,你必须在模型中编写accepts_nested_attributes_for并将它们添加到强参数中。像这样:

class Student < ActiveRecord::Base
  belongs_to :member
  has_many :trainings     
  accepts_nested_attributes_for :trainings
end

class StudentsController < ApplicationController
  def new
    @student = Student.new
    @student.trainings.build 
  end

  def create
    @student = Student.create(student_params)
    @student.trainings.build(params[:student][:trainings])

    redirect_to student_path
  end

  #For rails 4

  def student_params
     params.require(:student).permit(:id, :name, trainings_attributes: [ :id, :your fields here ])
    end
end

这是一个可以帮助您的链接: Rails 4: accepts_nested_attributes_for and mass assignment

答案 1 :(得分:0)

如果您已正确定义了关联,那么new控制器操作中的代码将起作用(我对其进行了测试)。检查并确保您的Training模型存在,或者您使用了正确的关联名称(也许您的意思是:teachers?)。

应用/模型/ student.rb

class Student < ActiveRecord::Base
  has_many :trainings
end

应用/模型/ training.rb

class Training < ActiveRecord::Base
  belongs_to :student
end

应用/控制器/ students_controller.rb

class StudentsController < ApplicationController
  def new
    @student = Student.new
    @student.trainings.build
  end
end

<强>更新

假设这些是您的关联定义的方式,您可以像这样构建一个范围Training的实例:

应用/模型/ member.rb

class Member < ActiveRecord::Base
  has_many :trainings
end

应用/模型/ student.rb

class Student < ActiveRecord::Base
  delegate :trainings, to: :member
  belongs_to :member
end

应用/模型/ training.rb

class Training < ActiveRecord::Base
  belongs_to :member
end

应用/控制器/ students_controller.rb

class StudentsController < ApplicationController
  def new
    @student = Student.new
    @student.build_member
    @student.trainings.build
  end
end

希望有所帮助。