Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 正在创建不在其中显示的属于模型的实例';关联对象列表_Ruby On Rails_Has Many_Polymorphic Associations_Belongs To - Fatal编程技术网

Ruby on rails 正在创建不在其中显示的属于模型的实例';关联对象列表

Ruby on rails 正在创建不在其中显示的属于模型的实例';关联对象列表,ruby-on-rails,has-many,polymorphic-associations,belongs-to,Ruby On Rails,Has Many,Polymorphic Associations,Belongs To,我创建了两个具有以下关联的模型 class User < ActiveRecord::Base has_many :roles, :dependent => :destroy end class Role < ActiveRecord::Base belongs_to :user end class Student < Role end class Tutor < Role end 我希望: #some user @user @user.roles

我创建了两个具有以下关联的模型

class User < ActiveRecord::Base
  has_many :roles, :dependent => :destroy
end

class Role < ActiveRecord::Base
  belongs_to :user
end

class Student < Role
end

class Tutor < Role
end
我希望:

#some user @user
@user.roles

有一个包含导师的数组。然而,它似乎不起作用。你知道我做错了什么吗?

一旦你开始使用单表继承,你创建的导师就不是一个角色了,就这种类型查询的活动记录而言

class User < ActiveRecord::Base
  has_many :roles
  has_many :tutors
end

@user = User.first
@user.roles
=> []

@user.tutors
=> [#<Tutor id: 1, user_id: 1, type: "Tutor", created_at: "2012-10-26 18:15:16", updated_at: "2012-10-26 18:15:16">]

[#,#]

@user只是user object的一个实例是的,我理解。但你在什么地方举例过吗?如果是的话,你是怎么做的?例如,您是否有类似于
@user=user.find(params[:id])
的东西?我正在处理以前创建的对象,但是的,它们在创建时就是这样实例化的。所以要么我得到您列出的角色,要么我必须更改继承的类型?如果我想让它像我之前列出的那样工作呢。我需要做哪些更改?您不能使用继承。这可能是唯一的办法。
class User < ActiveRecord::Base
  has_many :roles
  has_many :tutors
end

@user = User.first
@user.roles
=> []

@user.tutors
=> [#<Tutor id: 1, user_id: 1, type: "Tutor", created_at: "2012-10-26 18:15:16", updated_at: "2012-10-26 18:15:16">]
Role.where(user_id: @user.id).all