Datamapper同时有两个关联

时间:2012-07-01 09:07:40

标签: ruby sinatra datamapper

假设我有帖子,这篇文章应该有一定数量的评论,这些评论应该由certian用户创建。所以这些是我的datamapper模型:

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

[...]

基本上,Model Post应该与Model Comment和Model Post相关联,我该如何实现这一点?

1 个答案:

答案 0 :(得分:3)

comment = Comment.create :post => post, :user => user, :text => 'Foo'