Rails有许多在belongs_to的关系
问题描述:
在我的Rails应用程序,我有以下型号Rails有许多在belongs_to的关系
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
感谢
答
你必须写accepts_nested_attributes_for模型和强大的参数添加他们,如果你使用的是轨道4.就像这样:
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
答
如果你已经正确地定义了你的关联,那么你的new
控制器动作中的代码就可以工作(我测试了它)。检查并确保您的模型存在,或者您使用了正确的关联名称(也许您的意思是: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
app/models/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
希望有所帮助。
你的'训练'模型在哪里? – 2015-02-07 08:14:40
也,它会帮助我们,如果你发布你收到的错误。 – 2015-02-07 08:21:40