[英]Rails 'select as' nested model using scopes
我正在嘗試創建一個Rails作用域,該作用域允許我構造父子模型關聯,如下所示:
{
id: 1,
...other_child_attrs,
parent: {
id: 2,
...other_parent_attrs
}
}
我能“注入”的parent
在屬性child
通過使用以下查詢:
scope :include_parent, -> { Child.joins(:parent).select('childs.*, parents.*') }
問題在於,父級的嵌套屬性在與子級屬性相同的級別上注入(這可能會導致沖突,因為某些子級屬性在child- id
, created_at
等中重復):
{
id: 2, // Notice there's a parent - child id collision
...other_child_attrs,
...other_parent_attrs
}
是否可以僅使用活動記錄/普通sql來實現上述結構(而不必依賴序列化gem, as_json
等)?
試試這個,在模型中使用as_json來做
def as_json(options={})
super(:include => { :sales => {
:include => { :product => {
:only => [:id,:name, :price] } },
:only => :id} })
end
我認為您過於復雜了。 如果您已經正確配置了兩個具有關聯的模型,那么您已經可以做您想做的事情:
class Child < ActiveRecord::Base
belongs_to :parent
end
class Parent < ActiveRecord::Base
has_one :child
end
parent = Parent.create
child = Child.create(parent_id: parent.id)
child.to_json(include: :parent)
=> [{"id":1,"parent_id":1,"created_at":"2017-08-04T20:48:52.056Z","updated_at":"2017-08-04T20:48:52.056Z","parent":{"id":1,"created_at":"2017-08-04T20:47:32.671Z","updated_at":"2017-08-04T20:47:32.671Z"}}]
child = Child.first
child.parent
Child Load (0.2ms) SELECT "children".* FROM "children" ORDER BY "children"."id" ASC LIMIT ? [["LIMIT", 1]]
Parent Load (0.1ms) SELECT "parents".* FROM "parents" WHERE "parents"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<Parent id: 1, created_at: "2017-08-04 20:47:32", updated_at: "2017-08-04 20:47:32">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.