Rails RABL if else statement

I am using RABL in a Rails application to access data through REST. It works, 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
+5
source share
2 answers

If it matitem_idis an attribute of an object @expense, you must reference it in the conditional expression using the helper root_objectas follows:

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

It is also != nilprobably redundant.

+9
source

This line:

if :matitem_id != nil

Personally compares character :matitem_idc nil. This will NEVER be true. You need to compare the identifier of the child. You can pass an object to a block:

child :matitem do |matitem|
  if matitem.id != nil
    ...
end
+1
source

All Articles