Search code examples
ruby-on-railsrubyrabl

If condition on RABL


I have two attributes in my relation - flyer and flyer_url. I want to put an if condition which assigns either flyer or flyer_url to flyer_image_url depending on which is not null. All the records have either of them set to null. I've tried the following code but it is only assigning flyer_url to flyer_image_url even when it is null:

attribute :flyer => :flyer_image_url
attribute :flyer_url => :flyer_image_url, :if => lambda { |flyer_url| !flyer_url.nil? }

Please help! Thanks!!


Solution

  • Thanks to Nathan Esquenazi - the creator of RABL, I finally got the answer.

    This is a limitation (although somewhat intentional) of RABL, for a given key name “flyer_image_url” there should only ever be a single statement associated with it. Trying to have two statements associated with a single key is what is causing the confusion here.

    He suggests using a single node instead with custom logic: https://github.com/nesquena/rabl#custom-nodes

    node :flyer_image_url do |object|
       object.flyer_url.nil? ? object.flyer : object.flyer_url
       # This is just ruby, put whatever you want that ends up as a string
    end
    

    That worked like a charm! Hope this answer finds somebody!