Rails RABL if else statement
Asked Answered
Q

2

5

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
Quadrat answered 12/4, 2013 at 21:58 Comment(2)
What do you mean it is not working?Adriannaadrianne
Sorry - I changed the questions and added the errorQuadrat
I
9

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.

Intracardiac answered 12/4, 2013 at 22:56 Comment(0)
R
1

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
Ronnironnica answered 12/4, 2013 at 22:4 Comment(1)
Does your Expense model have belongs_to :matitem?Ronnironnica

© 2022 - 2024 — McMap. All rights reserved.