0

假设我有一个帖子,这个帖子应该有一定数量的评论,这些评论应该由一定的用户创建。所以这些是我的数据映射器模型:

class User
include DataMapper::Resource

property :id, Serial
property :name, String,
property :password, String

has n, :post
end

class Post
include DataMapper::Resource

property :id, Serial
property :text, Text
property :created_at, DateTime

belongs_to :user
end

class Comment
include DataMapper::Resource

property :text, Text,
property :created_at, DateTime

belongs_to :post
belongs_to :user
end

因此,假设用户 x 创建了一个帖子,而用户 y 想要对该帖子创建评论。那我该怎么做呢?我需要这样的东西:

user = User.get(sessions[:user_id])
post = Post.get(params[:post_id])
comment = post.user.Comment.new {
:text => "Bla",
[...]
}

[...]

comment.save

[...]

所以基本上模特帖子应该与模特评论和模特帖子相关联,我如何实现这一点?

4

1 回答 1

3
comment = Comment.create :post => post, :user => user, :text => 'Foo'
于 2012-07-01T15:53:47.317 回答