Kévin Furet
Kévin Furet

Reputation: 345

How to convert string to existing attribute in model when creation

I got a array of strings, I want to retrieve for each the attribute during the creation of the post.

My array = ["_646_maturity", "_660_maturity", "_651_maturity", "_652_maturity", "_641_maturity"]


class Audit < ApplicationRecord

  belongs_to :user

  before_save :calculate_scoring

  def calculate_scoring
    scoring = []

    models = ActiveRecord::Base.connection.tables.collect{|t| t.underscore.singularize.camelize.constantize rescue nil}
    columns = models.collect{|m| m.column_names rescue nil}

    columns[2].each do |c|
      if c.include? "maturity"
        Rails.logger.debug 'COLUMN : '+c.inspect
        scoring.push(c)
      end
    end

    getMaturity = ""

    scoring.each do |e|
       getMaturity = e.to_sym.inspect
       Rails.logger.debug 'MATURITY : '+getMaturity
    end


  end

end

The log print > 'MATURITY : :_651_maturity'

I'm looking to the value of :_651_maturity who is a attribute of my post.

I tried .to_sym but it's not working..

Thanks for the help!

Upvotes: 0

Views: 70

Answers (1)

CAmador
CAmador

Reputation: 1951

Inside calculate_scoring you can use self to point to the record you are saving. So self._651_maturity = <some_value>, self[:_651_maturity] = <some_value> and self['_651_maturity'] are all valid methods to set _651_maturity.

Also, you can do something like:

my_attrib = '_651_maturity'
self[my_attrib] = 'foo'

Upvotes: 1

Related Questions