我正在使用DataMapper和Sinatra来创建一个简单的应用程序。这是结构:
该应用有帐户。每个帐户都有用户和广告系列。每个用户都有与特定广告系列相关的评论。
理想情况下,评论应该有一个user_id和一个campaign_id来关联它们。
我如何将2联系在一起?这是我的代码不起作用:
class Account
include DataMapper::Resource
property :id, Serial
property :mc_username, String, :required => true
property :mc_user_id, String, :required => true
property :mc_api_key, String, :required => true
property :created_at, DateTime
property :updated_at, DateTime
has n, :users
has n, :campaigns
end
class User
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
property :email, String, :required => true
property :is_organizer, Integer
property :created_at, DateTime
property :updated_at, DateTime
belongs_to :account, :key => true
has n, :comments
end
class Campaign
include DataMapper::Resource
belongs_to :mailchimpaccount, :key => true
has n, :comments
property :id, Serial
property :cid, String
property :name, String
property :current_revision, Integer
property :share_url, Text, :required => true
property :password, String
property :created_at, DateTime
property :updated_at, DateTime
end
class Comment
include DataMapper::Resource
belongs_to :campaign, :key => true
belongs_to :user, :key => true
property :id, Serial
property :at_revision, Integer
property :content, Text
property :created_at, DateTime
end
使用此代码,我无法保存评论,因为我无法弄清楚如何将其与广告系列和用户同时关联。我无法真正理解我的想法,我甚至应该尝试使用DataMapper将它们联系起来。
我很想知道这段代码是否正确,如何创建与两者相关的评论。如果不是,那么这种情况下哪种结构和关联是最佳的?
非常感谢你的帮助!
答案 0 :(得分:1)
你正在做的事似乎是合理的,我认为你只需要摆脱:key => true
选项,因为你真的不希望这些关联成为评论主键的一部分。
答案 1 :(得分:1)
您应该首先查看这些datamapper docs on properties。
Alex是对的,你所拥有的是一个复合主键。如果您只希望每个用户每个广告系列都有一个评论,那就没问题了,但情况可能并非如此,但您确实希望确保评论与用户和广告系列相关联,因此请使用required =>是的,就像这样:
class Comment
include DataMapper::Resource
property :id, Serial
belongs_to :campaign, :required => true
belongs_to :user, :required => true
property :at_revision, Integer
property :content, Text
property :created_at, DateTime
end
此外,您在广告系列模型中的关键可能会出现问题:
class Campaign
include DataMapper::Resource
belongs_to :mailchimpaccount, :key => true
#......
你可能只是想要那样做。
答案 2 :(得分:1)
所以看来我的想法是正确的。我可以以这种方式将评论与用户和广告系列相关联:
# Get a user and a campaign first that we can relate to the comment
user = User.get(user_id)
campaign = Campaign.get(campaign_id)
comment = Comment.new
comment.content = "The comment's content"
user.comments << comment # This relates the comment to a specific user
campaign.comments << comment # This now relates the comment to a specific campaign
comment.save # Save the comment
Dangermouse建议用:key => true
替换:required => true
选项也有助于清理架构。谢谢!