[英]Active Record Associations in Rails
I have a model Persons::Names::Log
and another model Persons::Address
. 我有一个模型
Persons::Names::Log
和另一个模型Persons::Address
。 I want to create an association between Log
and Address
. 我想在
Log
和Address
之间创建一个关联。 Is it possible? 可能吗? What statements should I write in both the model files?
我应该在两个模型文件中写哪些语句?
Edit
: Edit
:
I want to have an association like Persons::Names::Log.last.address
我想拥有一个类似于
Persons::Names::Log.last.address
From http://guides.rubyonrails.org/association_basics.html#controlling-association-scope : 来自http://guides.rubyonrails.org/association_basics.html#controlling-association-scope :
To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration.
要将模型与其他命名空间中的模型关联,必须在关联声明中指定完整的类名。
The following is an example of the associations with the given class names: 以下是与给定类名的关联的示例:
module Persons
module Names
class Log
has_one :address, class_name: "Persons::Address"
end
end
class Address
belongs_to :log, class_name: "Persons::Names::Log"
end
end
Specify the class name with scopes : 用作用域指定类名:
# app/persons/names/log.rb
module Persons
module Names
class Log < ActiveRecord::Base
has_one :address, class_name: "Persons::Address"
end
end
end
# app/persons/address.rb
module Persons
class Address < ActiveRecord::Base
belongs_to :log, class_name: "Persons::Names::Log"
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.