2010-10-25 59 views
5

我創建一個論壇網站,在那裏每個註冊用戶可以寫很多職位和
各崗位能夠有很多的意見。
此外,每個用戶可以評論任何其他用戶創建的任何帖子。Rails:用戶的最佳關聯模型 - >帖子 - >評論模型在網站論壇中有點類似?

 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
如何實現這一目標?
粘貼我的模型以供參考: -

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

+0

如何創建評論?控制器? – 2013-01-20 15:58:54

回答

8

由於您的文章有很多評論,所以它是post.comments而不是post.comment

由於comments是的評論列表,comments.user無效也。

您需要評論的ID,這樣你可以找到具體的意見的用戶:

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

,你也可以得到所有用戶:

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