Matthew h Matthew h - 2 months ago 18
Ruby Question

Ruby search for comma seperated string

I am kind of new to Ruby on Rails and can't figure out how to store a string of numbers with commas in it into the database. Ever attempted I make at doing this it turns the the list into an array and takes the first item.

for example: "12,34,56,78,90" it would save this as 12

The same thing goes for when I am trying to search for that string. This doesn't make any sense to me why Rails wants to convert a string into an array and take the first element. I haven't been able to find away around this. Any help would be appreciated!

Below is the sample of my code that I want to get working.

if DeviceApprovalQueue.find_by_address(params[:address]).nil?
daq = DeviceApprovalQueue.new(device_id: params[:gateway_id], address: params[:address])
if daq.save
#Device is queued
end
else
#Already queued
end

Answer

This doesn't make any sense to me why Rails wants to convert a string into an array and take the first element.

Because this is not what happens here. You have an integer column. So 12 is the result of casting your string to integer.

'12,34,56,78,90'.to_i # => 12

Now you could store it in a string column, but then it's just a string. You lose all its properties as a "list of integers".

You could store it in array column. But this a) requires you to parse it beforehand and b) is not a widely supported column type.

Perhaps, you need to do something else. Hard to say.