开发者

Rails model belongs to model that belongs to model but i want to use another name

开发者 https://www.devze.com 2022-12-27 14:57 出处:网络
This may be a stupid question but im just starting to learn Rail thats why i am asking thsi question.

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:开发者_StackOverflow

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

Thanks in advance!


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
0

精彩评论

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

关注公众号