5

In Rails I'm rendering a json array, but I need one of the keys to have a variable name depending on the params. something like this:

render json: {
        key1: values,
        params[:type]: more_values,
        labels: some_lables
      }

obviously this doesn't work, but what will?

2
  • you miss a comma after key1: values Commented May 26, 2015 at 16:33
  • fixed it, unfortunate typo. Commented May 27, 2015 at 12:35

2 Answers 2

8

Use interpolation :

render json: {
        :key1 => values,
        :"#{params[:type]}" => more_values,
        labels: some_lables
      }
Sign up to request clarification or add additional context in comments.

Comments

2

Make a hash and render it as JSON.

h = { key1: values, labels: some_labels }
h[params[:type]] = more_values
render json: h.to_json

1 Comment

They are both essentially the same thing, but whatever works for you is perfectly fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.