PinkElephantsOnParade
PinkElephantsOnParade

Reputation: 6592

Ruby in Rails - dynamically mapping in a .map

EDIT: For clarification, I want the number of elements of the resultant array-of-arrays to change dynamically based on the # of platforms. I.e. I want [[35,"assetname","platname1","platname2","platname3"]], not [[35, "assetname, ["platname1", "platname2", "platname3"]]].

I am using datatables as a part of my Rails app. I have a method that generates an ActiveRecord association and passes it to map. The operative code looks like this:

assets.map do |asset|
[
  asset.id,
  asset.name,
  asset.thing
]

But I want to do something trickier - I want to dynamically make the number of entries in the resultant array to be larger based on the # of some other object. I have an object called Platforms... so something like this

assets.map do |asset|
[
  asset.id,
  asset.name,
  Platforms.all.each do |line|
     line.platform_name.to_s,
  end
]

The problem is... it appears to be a syntax problem. No matter what I do, I cannot get a setup like this to work. I tried to simplify - this works (showing 1 in the final column):

assets.map do |asset|
[
  asset.id,
  asset.name,
  [1].each do |line| line.to_s end
]

But try to break that out to having more than one element, and no dice:

assets.map do |asset|
[
  asset.id,
  asset.name,
  [1,2].each do |line| line.to_s end
]

This puts just "1,2" in the final column. Whereas I want 1, then 2 in their own two columns - not "1,2" in a singular column.

As far as the syntax errors I get when trying to do it with my actual object:

app/datatables/assets_datatable.rb:111: syntax error, unexpected keyword_end, expecting '=' app/datatables/assets_datatable.rb:142: syntax error, unexpected keyword_end, expecting ']'

How does one achieve this? What I want to achieve is to have a resultant array that has more elements for each # of Platforms.

Upvotes: 0

Views: 446

Answers (1)

jvillian
jvillian

Reputation: 20263

Assuming you have a model called Platform (not Platforms, since models are usually in the singular), it seems like this would be as simple as:

platform_names = Platform.pluck(:platform_name)

assets.map do |asset|
  [
    asset.id,
    asset.name,
    platform_names
  ]
end

Naturally, platform_names will be identical for each mapped asset, but I guess that's what you want?

Given your comment, you can try:

platform_names = Platform.pluck(:platform_name)

assets.map do |asset|
  [
    asset.id,
    asset.name
  ].concat(platform_names)
end

Or, as mu says:

platform_names = Platform.pluck(:platform_name)

assets.map do |asset|
  [
    asset.id,
    asset.name,
    *platform_names
  ]
end

Upvotes: 3

Related Questions