byCoder
byCoder

Reputation: 9184

Rails RABL display collection as object and child in this object

I have such index.rabl:

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

extends "exchanger_lists/show"

and such 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

my contoller is such:

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

if i call in browser show method, i see child @currencies and it's data, but if i call index i see all (also i see nodes) but child i didn't see.... What's wrong? what i do bad?

Upvotes: 0

Views: 1705

Answers (1)

dan
dan

Reputation: 1028

Your architecture is a little bit messed up because in the show action you not only display an @exchanger but also the complete list of @currencies being nil when you render show in the index template. In general I would suggest you to think about the whole app architecture.

When I should give you a simple solution for you current problem I would extract the @currencies code from the show action into helper method in app/helpers/currencies_helper.rb and access it from the show template.

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

By the way I replaced the each method with map because it suits better in this case.

Change the currencies part in the show template to

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

Upvotes: 1

Related Questions