Make condition within the surrender

Asked

Viewed 70 times

0

I’m learning Ruby and I’m having a question about how to make a if inside the render to display the param only if he exists...

Ex:

if params[:field]
  puts 'field'  =>  params[:field],
end

How do I fix it in this code?

render :json => {
    'request'=>{
        'negotiation'   =>  params[:negotiation],
        'state' =>  params[:state],
        'city'  =>  params[:city],
     },
    'response'=>lista,
}

abs!

1 answer

1


Mount the hash instead:

res = {
    'request'=>{ },
    'response'=>lista
}

Add the parameters like this:

res['request']['negotiation'] = params[:negotiation] if params[:negotiation]

res['request']['state'] = params[:state] if params[:state]

And make him surrender

render json: res
  • Can you tell me, why I can’t get this hash popular before instating it?

  • I don’t understand your doubt.

  • Because I cannot start by adding "res['request']['negotiation'] = x". Because I need to create the empty hash first?

  • Vc can, nothing prevents you from creating a hash res = {} and adding the necessary keys.

  • That, but why should I create it zeroed first? In PHP for example I don’t need to create a $array = array(), I can start directly with $array['key'] = value.

  • You can, but in your case as you want to do if to know which fields will or will not exist, it would not work. But nothing prevents you from declaring a hash like this: h = { 'key' : value }.

  • I understand your question. It is not possible to initialize as in php, ruby hashes and arrays have to be declared before they can be used.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.