2017-08-04 46 views
0

我試圖創建Rails範圍,讓我來構造一個父嵌套模型 - 如下子模型關聯:Rails的選擇爲「使用範圍

{ 
    id: 1, 
    ...other_child_attrs, 
    parent: { 
    id: 2, 
    ...other_parent_attrs 
    } 
} 

我能「注入」的在childparent屬性通過使用以下查詢:

scope :include_parent, -> { Child.joins(:parent).select('childs.*, parents.*') } 

的問題是,父母的嵌套屬性在同一水平作爲孩子的屬性注入(這可能會導致衝突,因爲一些孩子的屬性是孩子重複 - idcreated_at等):

{ 
    id: 2, // Notice there's a parent - child id collision 
    ...other_child_attrs, 
    ...other_parent_attrs 
} 

是否有可能實現上述結構與單獨的活動記錄/純SQL(解釋,而不必依賴於序列化寶石,as_json等)?

回答

0

試試這個,不要使用as_json的模型,可以

def as_json(options={}) 
    super(:include => { :sales => { 
           :include => { :product => { 
              :only => [:id,:name, :price] } }, 
           :only => :id} }) 
    end 
0

我認爲你是過於複雜這一點。如果您有兩種型號正確配置了關聯,那麼您已經可以做你想做的事情:

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">