Ruby on rails 对嵌入式模型的mongoid关联引用
我有以下设置Ruby on rails 对嵌入式模型的mongoid关联引用,ruby-on-rails,ruby-on-rails-3,mongodb,ruby-on-rails-3.1,mongoid,Ruby On Rails,Ruby On Rails 3,Mongodb,Ruby On Rails 3.1,Mongoid,我有以下设置 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 Cl
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
国家模式是所有国家的种子
国家通过嵌套形式在位置模型中存储其两个字母的短码。例如“我们”。
现在我想在视图中调用@company.location.country.name以获取“美国”,但是我得到了一个错误
undefined method `name' for nil:NilClass
我该怎么做呢?
最好的办法是什么?
我是MongoDB的新手,如果这是一个愚蠢的问题,我向您道歉。我认为您的问题与您在国家定义的反向关系有关。是的,一个位置可以有一个国家,但该国家不能链接到该位置,因为它是一个嵌入文档 尝试删除Country类中的
有多个:位置。这应该可以解决问题。如果不需要反向关系,请不要定义它
如果您需要反向关系,您可能不希望将其作为嵌入式文档。由于给定的原因(嵌入式和关系),这将不起作用
另一方面,对于您的问题,您不应该在数据库中存储国家的全名
事实上,这是一个“固定”列表,准确地说,它是ISO-3166-1。当有一个标准(罕见!)时,接受它。一个好的方法是使用区域设置(并且您不需要种子设定、同步和更新部分)
考虑到文件config/locales/iso-3166-1/en.yml
:
en:
countries:
AD: "Andorra"
AE: "United Arab Emirates"
AF: "Afghanistan"
AG: "Antigua and Barbuda"
...
fr:
countries:
AD: "Andorre"
AE: "Émirats arabes unis"
AF: "Afghanistan"
AG: "Antigua-et-Barbuda"
...
现在,您可以使用I18n.t(@mylocation.country,:scope=>:countries)
另外,它是i18n/l10n就绪:config/locales/iso-3166-1/fr.yml
:
en:
countries:
AD: "Andorra"
AE: "United Arab Emirates"
AF: "Afghanistan"
AG: "Antigua and Barbuda"
...
fr:
countries:
AD: "Andorre"
AE: "Émirats arabes unis"
AF: "Afghanistan"
AG: "Antigua-et-Barbuda"
...
为什么你没有一个有很多关系?