I create a forum site 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 cannot get user information about comments using "post.comment.user" or
commenter_email = comments.user.email
How to achieve this?
Insert 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 is my diagram: -
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 am using Rails 3.0.1.
suggest your thoughts.