【问题标题】:Accessing rails relationships with Ember.js使用 Ember.js 访问 rails 关系
【发布时间】:2026-01-12 21:05:01
【问题描述】:

我刚刚开始学习 ember,正在编写一个从数据库读取的简单应用程序。我已经让它以我想要的方式与固定装置一起工作,并且刚刚开始从数据库中读取一些进展。现在我的问题是我无法访问子元素 - 我有一个父类,我通过序列化程序使用 json 响应,并且我正在为 json 请求中的子元素提供服务。但是,我不知道从这里去哪里让 ember 中的父类读取和显示子元素。下面的代码可能更有意义。

如果您需要任何其他代码,请告诉我 - 这些都是标准的 Ember 代码,没有规范!我要继续的唯一线索是我当前的嵌套 ruby​​ 路由用作群组/:id/boots/:id,而使用夹具数据加载群组/:id/:id 时,ember :)

型号:

Plato.Boot = DS.Model.extend(
    name: DS.attr("string"),
    cohort: DS.belongsTo('Plato.Cohort'),
    hubs: DS.hasMany('Plato.Hub')
)
Plato.Cohort = DS.Model.extend(
  name: DS.attr('string'),
  boots: DS.hasMany('Plato.Boot')
)

Route.rb

  root to: 'application#index'

  resources :cohorts do
    resources :boots
  end

  resources :boots

群组(父)控制器

class CohortsController < ApplicationController
    respond_to :json
  def index
    respond_with Cohort.all
  end

  def show
    respond_with Cohort.find(params[:id])
  end
end

引导(子)控制器

class BootsController < ApplicationController
    respond_to :json
  def index
    respond_with Boot.all
  end

  def show
    respond_with Boot.find(params[:id])
  end
end

Router.js.coffee

Plato.Router.map ()->
    this.resource('cohorts', ->
    this.resource('cohort', {path: '/:cohort_id'}, ->
        this.resource('boot', {path: 'boots/:boot_id'})
    )
  )

Plato.CohortsRoute = Ember.Route.extend(
    model: ->
        Plato.Cohort.find()
)

Plato.BootsRoute = Ember.Route.extend(
    model: -> 
        Plato.Boot.find(params)
)

【问题讨论】:

    标签: javascript ruby-on-rails ruby ember.js ember-data


    【解决方案1】:

    您是否尝试在路由器映射中定义嵌入记录 boots

    例如:

    Plato.Adapter = DS.RESTAdapter.extend();
    
    Plato.Store = DS.Store.extend({
      adapter: Plato.Adapter
    });
    
    Plato.Adapter.map('Plato.Cohort', {
      boots: {embedded: 'always'}
    });
    

    这样嵌入的记录将与父记录一起加载。

    希望对你有帮助。

    【讨论】:

    • 我很高兴它有效,为什么{embedded: 'always'}的优点:)
    • 也许另一个问题的答案会帮助我理解 - 我想让嵌套深入两层,但我似乎无法重新创建或嵌套嵌入函数以用于最低层(第三层? ) 嵌套属性层-虽然我似乎找不到太多关于嵌入的信息,但我会继续寻找!我想这是由于我对 RESTAdapter 缺乏了解