Rails: Best association model for Users ->posts -> comments model in a forum kinda of website?
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-------------
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
Here my schema:-
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
I'm using Rails 3.0.1.
please suggest your thoughts.Since your post has many comments, so it is post.comments
instead of post.comment
Since comments
is a list of comments, comments.user
is not valid also.
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)
精彩评论