我有3个型号,但这种关联有点棘手。
首先我有用户,对于2种不同类型的用户,我有2种不同的个人资料模型,分别是Pteacher和Pstudent。
每个Pteacher都有1个Pstudent。
所以我制作了这样的模型;
class User < ActiveRecord::Base
validates_uniqueness_of :uname
has_many :pteachers
has_many :pstudents
end
class Pteacher < ActiveRecord::Base
has_one :pstudent
belongs_to :user
end
class Pstudent < ActiveRecord::Base
has_one :pteacher
belongs_to :user
end
现在,如果我首先选择用户而不是选择Pteacher而不是选择像User.pteacher.pstudent这样的Pstudent,它会给我No Method错误。
BUT
如果我直接选择Pteacher,我可以用Pteacher.pstudent选择Pstudent。
问题是我想通过User=>Pteacher=>Pstudent
有没有办法实现这个目标?
顺便说一句,我发现如果我是从用户创建的话,我无法达到任何Pteacher的方法。例如,如果我写入Rails控制台;
user = User.first #Which is a teacher
user.pteachers #This line gives me all the info about that users pteacher
#now funny part
pt = user.pteacher #this works too as now i have pt as a Pteacher which have all the data i want
pt.id #fails???
pt.name #fails???
pt.pstudent #fails???
pt #writes all info about pteacher which has id and name
答案 0 :(得分:0)
您希望将P_acher的关系从has_one更改为belongs_to。试一试,看看。
class Pstudent < ActiveRecord::Base
belongs_to :pteacher
belongs_to :user
end
另外,检查pteacher:
user = User.first # Which is a teacher
pt = user.pteachers.first # retrieving first teacher from list
p pt # prints out attributes of pt
答案 1 :(得分:0)
解决了! :d
问题是当我要求User.Pteachers.Pstudent时,实际上没有1个Pteacher它是Pteachers数组。所以User.Pteacher.first.Pstudent解决了它。
谢谢你们