ruby-on-rails - Mongoid - 具有引用数组的字段

标签 ruby-on-rails ruby mongoid

我是 mongoid 的新手,我有两个基本的(我认为)问题。在 Mongoid 中存储引用数组的最佳方法是什么。这是我需要的一个简短示例(简单投票):

{
  "_id" : ObjectId("postid"),
  "title": "Dummy title",
  "text": "Dummy text",
  "positive_voters": [{"_id": ObjectId("user1id")}, "_id": ObjectId("user2id")],
  "negative_voters": [{"_id": ObjectId("user3id")}]
}

这是正确的方法吗?

class Person
  include Mongoid::Document
  field :title, type: String
  field :text, type: String

  embeds_many :users, as: :positive_voters
  embeds_many :users, as: :negative_voters
end

还是错了?

我也不确定,对于这种情况来说,也许它的文档结构不好?如果用户已经投票并且不允许用户投票两次,我该如何优雅地获得?也许我应该使用另一种文档结构?

最佳答案

您可以选择 has_many,而不是 embeds_many,因为您只想在文档中保存选民的引用,而不是亲自保存整个用户文档

class Person
    include Mongoid::Document
    field :title, type: String
    field :text, type: String

    has_many :users, as: :positive_voters
    has_many :users, as: :negative_voters

    validate :unique_user

    def unique_user
       return self.positive_voter_ids.include?(new_user.id) || self.negative_voter_ids.include?(new_user.id)         
    end

end

关于ruby-on-rails - Mongoid - 具有引用数组的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10863474/

相关文章:

mysql - 加载 'mysql2' Active Record 适配器时出错

ruby-on-rails - 将许多环境变量传递给 Unicorn 运行的 Rails 应用程序

python - 在 `cd` 命令上运行 bash 脚本

ruby-on-rails - rails/rspec 看不到 shoulda 匹配器

ruby-on-rails - rails : Why images are not showing in my rails basic app

ruby-on-rails - 将数字添加到正则表达式?

ruby-on-rails - 显示 created_at 时未定义的方法 "getlocal"?

与指定类名的 Mongoid Habtm 关系

ruby-on-rails - Rails 标记和标记列表

ruby-on-rails - 使用 active_model_serializers 序列化模型数组