加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:用户的最佳关联模型 – >帖子 – &g

发布时间:2020-12-17 03:34:14 所属栏目:百科 来源:网络整理
导读:我正在创建一个论坛网站,每个注册用户都可以写很多帖子和 每个帖子都可以有很多评论. 此外,每个用户都可以评论由任何其他用户创建的任何帖子. has_many has_manyuser ------------ Posts -------------- Comments | ^ | | | has_many | |-------------------
我正在创建一个论坛网站,每个注册用户都可以写很多帖子和
每个帖子都可以有很多评论.
此外,每个用户都可以评论由任何其他用户创建的任何帖子.

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.
请提出您的想法.

解决方法

由于您的帖子有很多评论,所以它是post.comments而不是post.comment

由于comments是注释列表,comments.user也无效.

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

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

当然,你也可以得到所有用户:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读