Rails model belongs to model that belongs to model but i want to use another name
Posted
by Micke
on Stack Overflow
See other posts from Stack Overflow
or by Micke
Published on 2010-04-15T20:27:10Z
Indexed on
2010/04/15
20:43 UTC
Read the original article
Hit count: 913
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!
© Stack Overflow or respective owner