代码之家  ›  专栏  ›  技术社区  ›  Hemanth

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

  •  5
  • Hemanth  · 技术社区  · 14 年前

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

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

    1 回复  |  直到 14 年前
        1
  •  8
  •   PeterWong    14 年前

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

    自从 comments 是注释列表, comments.user 也无效。

    您需要注释的ID,以便找到特定注释的用户:

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

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

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