Rails:用户的最佳关联模型 -> 帖子 ->论坛中的评论模型有点像网站? [英] Rails: Best association model for Users ->posts -> comments model in a forum kinda of website?

查看:21
本文介绍了Rails:用户的最佳关联模型 -> 帖子 ->论坛中的评论模型有点像网站?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个论坛网站,每个注册用户都可以在其中写很多帖子和
每个帖子可以有很多评论.
此外,每个用户都可以评论任何其他用户创建的任何帖子.

I'm creating a forum website, where each registered user can write many posts and
each post can have many comments.
Also each user can comment on any posts created by any-other user.

      has_many              has_many
user ------------> Posts -------------- > Comments  
  |                                          ^
  |                                          |   
  |               has_many                   |
  |-------------------------------------------          
      belongs_to
Post ------------> User
  ^                 ^ 
  |                 |
  |                 |
  belongs_to     belongs_to
  |                 |
  |                 |
Comments-------------  

我无法使用post.comment.user"或
获取评论的用户详细信息commenter_email = comments.user.email
如何实现这一目标?
粘贴我的模型以供参考:-

I'm not able to get the user details of a comment using "post.comment.user" or
commenter_email = comments.user.email
How to achieve this ?
Pasting my models for reference :-

class Comment < ActiveRecord::Base  
belongs_to :post  
belongs_to :user  
end  
class Post < ActiveRecord::Base  
  has_many :comments, :dependent => :destroy  
end  
class User < ActiveRecord::Base  
  devise :database_authenticatable, :registerable,  
     :recoverable, :rememberable, :trackable, :validatable  
  attr_accessible :email, :password, :password_confirmation, :remember_me   
  has_many :posts  
  has_many :comments  
end   

这里是我的架构:-

create_table "comments", :force => true do |t|  
t.integer  "post_id"  
t.integer  "user_id"  
t.text     "comment_text"  
t.datetime "created_at"  
t.datetime "updated_at"  
end  

create_table "posts", :force => true do |t|  
t.integer  "user_id"  
t.integer  "sell_or_buy"  
t.string   "title"  
t.text     "body"  
t.datetime "created_at"  
t.datetime "updated_at"  
end  

create_table "users", :force => true do |t|  
t.string   "email",  
t.string   "encrypted_password",
t.datetime "created_at"  
t.datetime "updated_at"  
end 

我使用的是 Rails 3.0.1.
请提出你的想法.

I'm using Rails 3.0.1.
please suggest your thoughts.

推荐答案

由于你的帖子有很多评论,所以是post.comments而不是post.comment

Since your post has many comments, so it is post.comments instead of post.comment

由于 comments 是一个评论列表,comments.user 也无效.

Since comments is a list of comments, comments.user is not valid also.

您将需要评论的 id,以便您可以找到特定评论的用户:

You will need the comment's id so that you could find the specific comment's user:

post.comments.find(params[:id]).user

当然,您也可以获取所有用户:

of course, you could also get all users:

post.comments.all.collect(&:user)

这篇关于Rails:用户的最佳关联模型 -> 帖子 ->论坛中的评论模型有点像网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆