ruby - 使用 Sinatra 将一个类关联到 DataMapper 中的两个不同类

标签 ruby associations sinatra datamapper

我正在使用 DataMapper 和 Sinatra 创建一个简单的应用程序。结构如下:

该应用程序有帐户。每个帐户都有用户和事件。每个用户都有应该与特定事件相关的评论。

评论最好有一个 user_id 和一个 campaign_id 来关联它们。

如何将两者联系起来?这是我无法使用的代码:

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 将它们关联起来。

我很想知道这段代码是否正确,我该如何着手创建与两者相关的评论。如果不是,哪种结构和关联最适合这种情况?

非常感谢您的帮助!

最佳答案

你所做的似乎是合理的,我认为你只需要摆脱 :key => true 选项,因为你真的不希望这些关联成为评论主要部分的一部分键。

关于ruby - 使用 Sinatra 将一个类关联到 DataMapper 中的两个不同类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632228/

相关文章:

ruby - 如何强制 JRuby 使用 java Longs 而不是 Fixnums 初始化 java ArrayList?

sql - Rails,在最后一个之前找到对象,例如 -1

ruby - 如何使用 Paypal 的 Adaptive Payments API 和 Ruby 避免身份验证和时间问题?

ruby - 在继承方面如何为ruby中的类定义 "<"?

mysql - 查询关联表的外键

ruby-on-rails - 自引用问题 has_many :through associations in Rails

ruby-on-rails - 作用域关联上的 Rails 中的 counter_cache

ruby - 检查 Sinatra/DataMapper 中是否存在记录

ruby - 找不到类(class)

ruby - Sinatra 的良好表单助手?