与 Mongoid 的关联
我有三个简单的模型 - Car
、Details
和 Details2
。 Car
有很多 Details
,Details
有很多 Details2
。
使用 MySQL 和 ActiveRecord,我将设置如下关联:
class Car
has_many :details
end
class Detail
belongs_to :car
end
在视图中,我有一个汽车列表,我有:
<% @cars.each do |car| -%>
<%=car.details.count%> #uninitialized constant Details
<% end %>
EDIT2: 这是我在 cars 表中的内容:
db.cars.find()
{ "_id" : ObjectId("4efe69716f85ce447a000054"), "name" : "bmw", "descr" : "asasgasga as gas gas ", "updated_at" : "Sat Dec 31 2011 02:46:25 GMT+0100 (CET)", "created_at" : "Sat Dec 31 2011 02:46:25 GMT+0100 (CET)" }
和 details:
db.details.find()
{ "_id" : ObjectId("4f01106d6f85ce6b850000b8"), "car_id" : ObjectId("4efe69716f85ce447a000054"), "name" : "20120102030325", "descr" : "dsg", "updated_at" : "Mon Jan 02 2012 03:03:25 GMT+0100 (CET)", "created_at" : "Mon Jan 02 2012 03:03:25 GMT+0100 (CET)" }
在 CarsController 中,我仅在此操作中拥有:
def index
@cars = Car.all
end
这就是我所做的全部。
I have three simple models - Car
, Details
and Details2
.Car
have lot of Details
and Details
have lot of Details2
.
With MySQL and ActiveRecord I will set the associations like:
class Car
has_many :details
end
class Detail
belongs_to :car
end
In the view, where I have a list of Car, I have:
<% @cars.each do |car| -%>
<%=car.details.count%> #uninitialized constant Details
<% end %>
EDIT2:
This is what I have in cars table:
db.cars.find()
{ "_id" : ObjectId("4efe69716f85ce447a000054"), "name" : "bmw", "descr" : "asasgasga as gas gas ", "updated_at" : "Sat Dec 31 2011 02:46:25 GMT+0100 (CET)", "created_at" : "Sat Dec 31 2011 02:46:25 GMT+0100 (CET)" }
and details:
db.details.find()
{ "_id" : ObjectId("4f01106d6f85ce6b850000b8"), "car_id" : ObjectId("4efe69716f85ce447a000054"), "name" : "20120102030325", "descr" : "dsg", "updated_at" : "Mon Jan 02 2012 03:03:25 GMT+0100 (CET)", "created_at" : "Mon Jan 02 2012 03:03:25 GMT+0100 (CET)" }
And in CarsController I have in this action only:
def index
@cars = Car.all
end
that's all what I do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以重用从 ActiveRecord 中了解到的信息。
has_many
和belongs_to
工作正常在 Mongoid 中很好。但是您可以利用文档数据库(MongoDB 就是)并使用一些嵌入。为了使
embedded_in
正常工作,您必须在另一端安装embeds_one
或embeds_many
。请参阅http://mongoid.org/docs/relations/embedded/1-1。 htmlYou can reuse what you know from ActiveRecord.
has_many
andbelongs_to
work just fine in Mongoid.But you can take advantage of document databases (which MongoDB is) and use some embedding. For
embedded_in
to work correctly you have to haveembeds_one
orembeds_many
on the other end. See http://mongoid.org/docs/relations/embedded/1-1.html