首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在创建时将字符串转换为模型中已有的属性

如何在创建时将字符串转换为模型中已有的属性
EN

Stack Overflow用户
提问于 2019-06-05 01:54:43
回答 1查看 22关注 0票数 0

我得到了一个字符串数组,我想在创建帖子时检索每个字符串数组的属性。

我的数组= ["_646_maturity", "_660_maturity", "_651_maturity", "_652_maturity", "_641_maturity"]

代码语言:javascript
复制
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

日志打印> 'MATURITY : :_651_maturity'

我正在寻找:_651_maturity的值,它是我的帖子的一个属性。

我试过.to_sym,但它不工作..

谢谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-05 03:18:59

calculate_scoring中,您可以使用self指向要保存的记录。因此,self._651_maturity = <some_value>self[:_651_maturity] = <some_value>self['_651_maturity']都是设置_651_maturity的有效方法。

此外,您还可以执行以下操作:

代码语言:javascript
复制
my_attrib = '_651_maturity'
self[my_attrib] = 'foo'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56449071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档