简体   繁体   English

Rails模型关联问题

[英]Problem with Rails Model Associations

I have got 3 models, but the association is a little tricky. 我有3个模型,但是关联有些棘手。

First i've got Users, and for 2 different types of users i have 2 different profile models which are Pteacher and Pstudent. 首先,我有用户,对于2种不同类型的用户,我有2种不同的配置文件模型,分别是Pteacher和Pstudent。

The thing is also every Pteacher has 1 Pstudent. 事情是每位教师也有一名学生。

So i made the models like this; 所以我做了这样的模型;

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

And now, if i go through first selecting the User than selecting Pteacher than selecting Pstudent like User.pteacher.pstudent, it gives me No Method error. 现在,如果我先选择User而不是选择Pteacher而不是选择Pstudent之类的User.pteacher.pstudent,它给了我No Method错误。

BUT

If i select Pteacher directly, than i can select Pstudent with Pteacher.pstudent. 如果我直接选择Pteacher,则可以使用Pteacher.pstudent选择Pstudent。

The problem is i want to go through User=>Pteacher=>Pstudent 问题是我想通过User=>Pteacher=>Pstudent

Is there a way to achieve this? 有没有办法做到这一点?

By the way, i find out that i cannot reach any of Pteacher's methods if i create it from User. 顺便说一句,我发现如果我从用户创建它,我将无法达到Pteacher的任何方法。 For example, if i write to Rails Console; 例如,如果我写到Rails Console;

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

You want the change the relationship from has_one to belongs_to for Pteacher. 您想要将关系从has_one更改为Pteacher的belongs_to。 Try it out and see. 试试看,看看。

class Pstudent < ActiveRecord::Base 
    belongs_to :pteacher
    belongs_to :user
end

And also, retrieve the pteacher as so: 而且,按以下方式检索教师:

user = User.first # Which is a teacher
pt = user.pteachers.first # retrieving first teacher from list
p pt # prints out attributes of pt

Solved it ! 解决了! :D :D

The problem was when i ask for User.Pteachers.Pstudent, there is not 1 Pteacher actually it is a Pteachers array. 问题是当我要求User.Pteachers.Pstudent时,没有1个Pteacher实际上是一个Pteachers数组。 So User.Pteacher.first.Pstudent solved it. 所以User.Pteacher.first.Pstudent解决了它。

Thanks guys 多谢你们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM