【问题标题】:Rails RABL display collection as object and child in this objectRails RABL 将集合显示为对象和此对象中的子对象
【发布时间】:2013-04-24 11:06:54
【问题描述】:

我有这样的 index.rabl:

collection @exchangers, :root => "bank", :object_root => false

extends "exchanger_lists/show"

等show​​.rabl:

object @exchanger
attributes :id, :name, :address, :location_id, :latitude, :longitude, :exchanger_type_id
node(:location_name) {|exchanger_list| exchanger_list.location.name }
node(:exchanger_type_name) {"normal" }
child @currencies do
      attribute :value, :direction_of_exchange_id, :exchanger_list_id
end

我的控制器是这样的:

def index
    @exchangers = ExchangerList.all
  end
 def show
    @exchanger = ExchangerList.find(params[:id])
    @currency_list = CurrencyList.all
    @currencies = []
    @currency_list.each do |c|
      @currencies << CurrencyValue.find(:all, :conditions => {:currency_list_id => c.id, :exchanger_list_id => @exchanger.id}, :order => :updated_at).last(2)
    end
    @currencies.flatten!
  end

如果我在浏览器显示方法中调用,我会看到子 @currencies 和它的数据,但如果我调用索引,我会看到所有(我也看到节点),但我没有看到子子......怎么了?我做错了什么?

【问题讨论】:

  • 您的意思是您看不到@currencies 子节点吗?当您调用 index 并仅渲染显示模板时,此实例变量将为 nil。
  • @dan 是的,也许你是对的......但是我该如何解决我的问题呢?
  • 我没有忽略你,因为评论空间不足,我发布了答案。

标签: ruby-on-rails json rabl


【解决方案1】:

您的架构有点混乱,因为在 show 操作中,当您在索引模板中渲染 show 时,您不仅会显示 @exchanger,而且还会显示 @currencies 的完整列表为零。一般来说,我建议您考虑整个应用架构。

当我应该为你当前的问题提供一个简单的解决方案时,我会将 @currencies 代码从 show 操作中提取到 app/helpers/currencies_helper.rb 中的辅助方法中,并从 show 模板中访问它。

module CurrenciesHelper

  def currencies(exchanger)
    currencies = CurrencyList.all.map do |c|
      CurrencyValue.find(:all, :conditions => {:currency_list_id => c.id, :exchanger_list_id => exchanger.id}, :order => :updated_at).last(2)
    end
    currencies.flatten!
  end

end

顺便说一句,我用map 替换了each 方法,因为它更适合这种情况。

将显示模板中的货币部分更改为

child currencies(@exchanger) do
  attribute :value, :direction_of_exchange_id, :exchanger_list_id
end

【讨论】:

  • 好的,会试试的,请在视图和方法中添加关于然后写什么的信息
  • 在显示操作中一切正常,但在视图中我得到 Called id for nil,这可能错误地为 4,因为并非 db 中的所有数据都已链接,并非所有交换器都有currency_values....抓住它并解决它是真的吗?
  • 哟,对不起,我忘记了辅助方法中的交换器属性,我更新了我的答案。
  • hm( 真的很奇怪,但现在不行……只有当我删除 :exchanger_list_id => exchange.id 然后一切正常
  • 好的,但这似乎是可用数据的问题,正如我告诉你的那样,你的架构通常有点混乱,例如我不知道为什么您的 exchange_list_id 与 exchange.id 相同,我只是回答了您为什么在调用索引操作时没有显示货币的问题
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多