【问题标题】:mongoid association reference to an embedded model对嵌入式模型的 mongoid 关联引用
【发布时间】:2012-07-02 23:31:39
【问题描述】:

我有以下设置

Class Country
  include Mongoid::Document

  field :name
  field :code

  has_many :locations
end

Class Location
  include Mongoid::Document

  field :country
  field :region
  field :city

  has_many :locations
  embedded_in :company
end

Class Company
  include Mongoid::Document

  field :name

  embeds_one :location
  accepts_nested_attributes_for :location
end

Countries 模型包含所有国家/地区。

国家/地区通过嵌套形式存储在 Location 模型中的 2 个字母短代码。例如“美国”。 现在我想在视图中调用@company.location.country.name 以获取“美国”,但是我收到一个错误

undefined method `name' for nil:NilClass

我该怎么做呢? 最好的方法是什么? 我是 MongoDB 新手,所以如果这是一个愚蠢的问题,我深表歉意

【问题讨论】:

  • 你为什么没有has_and_bleongs_to_many 关系?

标签: ruby-on-rails ruby-on-rails-3 mongodb ruby-on-rails-3.1 mongoid


【解决方案1】:

我认为您的问题与您在 Country 上定义的反向关系有关。是的,位置可以有一个国家,但国家不能链接到该位置,因为它是一个嵌入式文档。

尝试删除 Country 类中的 has_many :locations。这应该解决它。如果不需要,不要定义反向关系。

如果您需要反向关系,您可能不希望它作为嵌入文档。

【讨论】:

    【解决方案2】:

    由于给定的原因(嵌入式和关系),这将不起作用。

    另一方面,对于您的问题,您不应将国家/地区的全名存储在您的数据库中。

    确实,这是一个“固定”列表,准确地说,它是 ISO-3166-1。当有标准时接受标准(罕见!)。一个好方法是使用语言环境(您可以省去播种、同步、更新部分)。

    考虑文件config/locales/iso-3166-1/en.yml

    en:
      countries:
        AD: "Andorra"
        AE: "United Arab Emirates"
        AF: "Afghanistan"
        AG: "Antigua and Barbuda"
        ...
    

    现在,您可以使用I18n.t(@mylocation.country, :scope => :countries)

    奖励,它已准备好 i18n / l10n:config/locales/iso-3166-1/fr.yml

    fr:
      countries:
        AD: "Andorre"
        AE: "Émirats arabes unis"
        AF: "Afghanistan"
        AG: "Antigua-et-Barbuda"
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2016-03-14
      相关资源
      最近更新 更多