开发者

Problem with Rails Model Associations

I have got 3 models, but the association is a little tricky.

First i've got Users, and for 2 different types of users i have 2 different profile models which are Pteacher and 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.

BUT

If i select Pteacher directly, than i can select Pstudent with Pteacher.pstudent.

The problem is i want to go through 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. For example, if i write to 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. 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

The problem was when i ask for User.Pteachers.Pstudent, there is not 1 Pteacher actually it is a Pteachers array. So User.Pteacher.first.Pstudent solved it.

Thanks guys

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜