Rails:论坛类网站中用户->帖子->评论模型的最佳关联模型?

2024-01-12

我正在创建一个论坛网站,每个注册用户都可以在其中撰写许多帖子并
每个帖子可以有很多评论。
此外,每个用户都可以对任何其他用户创建的任何帖子发表评论。

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

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

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。
请提出你的想法。


由于你的帖子有很多评论,所以post.comments代替post.comment

Since comments是评论列表,comments.user也无效。

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

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

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

post.comments.all.collect(&:user)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails:论坛类网站中用户->帖子->评论模型的最佳关联模型? 的相关文章

随机推荐