Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails RABL if else statement

I'm using RABL in a Rails app to access data via REST. It's working except for the if statement.

I get this error:

undefined local variable or method `matitem_id'

This is my show.json.rabl code:

object @expense
attributes :id, :unitcost, :quantity, :markup, :exp_date, :created_at, :description, :pcard, :invoice

child :employee do
  attributes :id, :maxname
end

child :vendor do
  attributes :id, :vendor_name
end

if matitem_id != nil
  child :matitem do |matitem|
    attributes :id, :itemnum
  end
end

UPDATE1

I also tried

if @expense.matitem_id != nil
like image 617
Reddirt Avatar asked Apr 12 '13 21:04

Reddirt


2 Answers

If matitem_id is an attribute of the @expense object you should reference it in a conditional through the root_object helper like this:

if root_object.matitem_id
  child :matitem do |matitem|
    attributes :id, :itemnum
  end
end

Also, the != nil is probably redundant.

like image 159
Andrew Hubbs Avatar answered Sep 27 '22 23:09

Andrew Hubbs


This line:

if :matitem_id != nil

Is literally comparing the symbol :matitem_id to nil. This will NEVER be true. What you need to do is compare the ID of the child object. You can pass the object into the block:

child :matitem do |matitem|
  if matitem.id != nil
    ...
end
like image 45
Logan Serman Avatar answered Sep 27 '22 23:09

Logan Serman