2015-02-07 91 views
0

在我的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 

感谢

+0

你的'训练'模型在哪里? – 2015-02-07 08:14:40

+0

也,它会帮助我们,如果你发布你收到的错误。 – 2015-02-07 08:21:40

回答

0

你必须写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

+0

目前他们的问题无关“accept_nested_attributes_for”;相反,他们不能构建'Training'的范围实例。 – 2015-02-07 08:33:33

+0

感谢您的答复。这里的问题是我不喜欢trainig上的(student_id和teacher_id)列。我更喜欢只有member_id。我希望现在很清楚 – Tiamon 2015-02-07 08:44:53

+0

顺便说一下,我有accepted_nested_attributes和使用强参数 – Tiamon 2015-02-07 08:45:55

0

如果你已经正确地定义了你的关联,那么你的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 

希望有所帮助。

+0

我希望模型训练属于模型而不是学生。那可能吗? – Tiamon 2015-02-07 08:43:03

+0

你能说清楚吗?你想'培训'到'belongs_to'哪个型号? – 2015-02-07 08:45:12

+0

请再次检查,我已编辑它。我希望它属于成员 – Tiamon 2015-02-07 08:48:43