Rails 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

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

你的架构有点混乱,因为在show动作中,你不仅显示@exchanger,而且当你在索引模板中呈现show时,@currencies的完整列表为nil。总的来说,我建议你考虑整个应用程序的架构。

当我应该给你一个简单的解决方案,你当前的问题,我会提取@货币代码从显示行动到助手方法在app/helpers/currencies_helper。

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方法,因为它更适合这种情况。

将show模板中的currency部分更改为

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

相关内容

  • 没有找到相关文章

最新更新