views:

86

answers:

1

Hello. This may be a stupid question but im just starting to learn Rail thats why i am asking thsi question.

I have one model called "User" which handles all the users in my community. Now i want to add a guestbook to every user. So i created a model called "user_guestbook" and inserted this into the new model:

belongs_to :user

and this into the user model:

has_one :user_guestbook, :as => :guestbook

The next thing i did was to add a new model to handle the posts inside the guestbook. I named it "guestbook_posts" and added this code into the new model:

belongs_to :user_guestbook

And this into the user_guestbook model:

has_many :guestbook_posts, :as => :posts

What i wanted to achive was to be able to fetch all the posts to a certain user by:

@user = User.find(1)
puts @user.guestbook.posts

But it doesnt work for me. I dont know what i am doing wrong and if there is any easier way to do this please tell me so.

Just to note, i have created some migrations for it to as follows:

create_user_guestbook:

  t.integer :user_id

create_guestbook_posts:

  t.integer :guestbook_id
  t.integer :from_user
  t.string :post

Thanks in advance!

+2  A: 

I think it should be:

#user
has_one :guestbook, :class_name => "UserGuestbook"

#user_guestbook
belongs_to :user
has_many :posts, :class_name => "GuestbookPost"

#guestbook_posts
belongs_to :user_guestbook

To get all posts that belongs to a single user, you can add this line to the user's model

has_many :posts, :through => :guestbook

And then, call this:

@user.posts
j.
will try this. thanks
Micke
I'm getting "can't convert class into strin" when doing @user = User.find 1 and then @user.guestbook
Micke
The code missed quoted around the value of `class_name`. Try the updated code.
KandadaBoggu
Yeah, i noticed that. It works now :) tanks!
Micke
@KandadaBoggu, i missed that. thank you :]
j.