Ruby on rails ActiveRecord赢得';t使用STI构建正确的类
我在应用程序中使用单表继承,从祖先构建继承的用户时遇到问题。例如,使用以下设置:Ruby on rails ActiveRecord赢得';t使用STI构建正确的类,ruby-on-rails,ruby-on-rails-3,activerecord,sti,Ruby On Rails,Ruby On Rails 3,Activerecord,Sti,我在应用程序中使用单表继承,从祖先构建继承的用户时遇到问题。例如,使用以下设置: class School < ActiveRecord::Base has_many :users end class User < ActiveRecord::Base attr_accessible :type #etc... belongs_to :school end Class Instructor < User attr_accessible :te
class School < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
attr_accessible :type #etc...
belongs_to :school
end
Class Instructor < User
attr_accessible :terms_of_service
validates :terms_of_service, :acceptance => true
end
Class Student < User
end
班级学校true
结束
班级学生<用户
结束
如何从学校的实例中创建
讲师
或学生
记录?尝试类似于School.first.instructors.build(…)
的操作只会给我一个新的用户实例,我将无法访问特定于讲师的字段,例如服务条款
在生成特定于讲师的表单时导致错误,从控制台生成将给我一个批量分配错误(因为它试图创建用户记录,而不是指定的讲师记录)。我给出了School的示例,但我希望从用户表继承一些其他关联,因此不必重复数据库中的代码或字段。我遇到这个问题是因为在STI设置中不能共享关联吗?您应该明确指定讲师
class School < ActiveRecord::Base
has_many :users
has_many :instructors,:class_name => 'Instructor', :foreign_key => 'user_id'
end
班级学校“讲师”,:foreign\u key=>“用户id”
结束
还有什么:
class School < ActiveRecord::Base
has_many :users
has_many :instructors
end
class Instructor < User
attr_accessible :terms_of_service # let it be at the first place. :)
validates :terms_of_service, :acceptance => true
end
班级学校true
结束
好的,问题的一部分似乎是由于在我的学校的模型中有旧的用户关联。删除这一点并增加学生和教师各自的协会是有效的
更新了School.rb:
class School < ActiveRecord::Base
#removed:
#has_many :users this line was causing problems
#added
has_many :instructors
has_many :students
end
班级学校
不起作用,我添加了该代码并运行了School.last.instructors.build(:terms\u of_service=>true)
并得到了一个批量分配错误,因为它仍然认为这是一个用户记录。@Cyle在构建School.first.instructors.build时也尝试指定一个类型。@type:'Instructor')
@Cyle您也可以尝试说user=School.first.instructors.build(…);user.been('讲师')
Hmm,您的最后一个代码片段生成错误NoMethodError:undefined method'new'“讲师”:String
Guys,您没有这些东西,您不必:class\u name=>'讲师',:foreign\u key=>'user\u id'。原因:用户id?此关联的外键必须是:school\u id
。换句话说,有很多:讲师。就是这样。STI关系中共享了关联,但学校不知道这一点,你必须为学校实施新的关联,如下一个答案中所示。尝试过了,我是否必须向数据库中添加任何其他字段才能使该方法起作用?(这有点违背STI的目的)不,只需正确设置STI:使用字段“type”数据类型字符串,重新加载环境。它应该会起作用。如果没有,请提供更多代码,以便我们了解错误所在。