0

I need to render a JSON in Rails but before I want to verify a boolean from my class, (e.g. Stores) which have "published" boolean.

I've tried something like that:

json.extract! @store

   json.store do

      if @store.published true
         json.array! (@store) do |store|
           json.id store.id
           json.published store.published
     end
   end
 end
Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
Gehlen
  • 160
  • 1
  • 15
  • 1
    not positive what you're trying to do overall...but the conditional should be `if @store.published == true` – toddmetheny Mar 16 '16 at 03:55
  • I'd recommend you do all this logic in the controller. Any particular reason why you didn't? – Jerry Mar 16 '16 at 04:45
  • @toddmetheny I'll try that, thanks! – Gehlen Mar 16 '16 at 12:16
  • And @Jerry, actually I'm new programming, so I'm learning (btw its my first ask here, and I don't know why, but a lot of the question has gone.. o.o). And at first look, I just thought to do this directly on jsbuilder. After all, I think it will be easy to fix.. I think. I'm unable to try now, but when I do, I come back to tell you guys. Thaanks in advance! – Gehlen Mar 16 '16 at 12:17
  • @Jerry, I couldn't do this.. I have another class, "Regions", and json comes there.. like "@region.stores". Could you give a light? – Gehlen Mar 17 '16 at 00:12
  • @Gehlen I don't get the question. Need more context. – Jerry Mar 17 '16 at 05:23
  • @Jerry Ok, let me try to explain.. I have this iOS application, which get information from my (very very basic rails api) rails app.. So, in this case I need to get "Region" from api, which comes with "Stores".. So JSON file is like Regions { Stores [] }... Buut now I have to check a boolean from Stores, and get only "valid" stores.. And stores comes with regions.Tha thing is: I've added the boolean (published) in store table as well. But when I try to render from jbuilder, rails just get that error "published variable no found bla bla.." Anyway, like this.. I'll update my question to show! – Gehlen Mar 17 '16 at 11:23

1 Answers1

1

I had a similar application where I needed to filter out on a boolean value.

Here is what I did:

json.extract! block
    if block.visible?
        json.id block.id
        json.name block.name
        json.html block.html
        json.url block_url(block, format: :json)
    end

Basically using json.extract! I then filtered by my boolean visible and outputted the information I needed.

This is all handled within your JBuilder file.

DavidA26
  • 136
  • 6