Igor Martins Igor Martins - 7 months ago 12
Ruby Question

Structure json inside controller

I need to do a json structure like this, but with more than 1 items:

charge = {
items: [{
name: "Product A",
value: 1000,
amount: 2
}]
}


I have an
@items
that is
@items.pluck(:name, :price)

And I'm trying to create my json like this:

charge = {
items: [{
@items.each do |item|
'name:' = item.name,
'value:' = item.price,
'amount:' = 2
end
}]
}


And return this error:

SyntaxError in CoursesController#qualquer

syntax error, unexpected '=', expecting keyword_end
'name:' = item.name,


How i do this structure?

Answer

There are two things I see wrong. First, you're using "=" operator to set a Ruby Hash value. That's not correct, as Ruby hashes use symbols or strings. So your hash values will need to look like this:

{ "may_hash_key" => my.has_value }

or

{ my_hash_key: my.hash_value }

or

{ :may_hash_key => my.has_value }

Take your pick.

Additionally, if you are rendering JSON from your controller action, you can do something like this:

def index
  # presumably some setup code
  charge = {
    items: @items.map do |item| {
      name:   item.name,
      value:  item.price,
      amount: 2
    }
  }
  render json: charge
end

If you are not rendering JSON from your controller action, what you can do is set @charge and interact with it as a Ruby hash in your view instead.