【问题标题】:Rails: How to initialize an object with the attributes in strings?Rails:如何使用字符串中的属性初始化对象?
【发布时间】:2013-07-04 18:29:07
【问题描述】:

可能是在这个太长、草率的设计上工作,或者两者兼而有之。我的问题是我有一个想要初始化的模型。该对象有 52 个属性,但我只设置了大约 25 个,具体取决于我刚刚扫描的对象。当我扫描一个对象时,我会得到列并将它们与我创建的 hash_map 匹配。

哈希映射示例

这只是将扫描的文本与其各自的属性名称匹配。

hash_map = {"Pizza."=>"pizza_pie","PastaBowl"=>"pasta_bowl","tacos"=>"hard_shell_taco","IceCream"=>"ice_cream","PopTarts"=>"pop_tart"}

我想做的事

menu = RestaurantMenu.new(pizza_pie => var1, pasta_bowl => var2, ...)

目前我唯一的问题是在我的代码中......

t.rows.each do |r|
  for i in 0..r.length-1
     #hash_map[t.combined_columns[i]] => r.[i]
     puts "#{hash_map["#{t.combined_columns[i]}"]} => #{r[i]}"
  end
end

puts 行显示了我想要的内容,但不确定如何在我的应用中正确获取它。

【问题讨论】:

    标签: ruby-on-rails initialization hashmap


    【解决方案1】:

    这里有几种解决方法:

    hash_map = {"Pizza."=>"pizza_pie","PastaBowl"=>"pasta_bowl","tacos"=>"hard_shell_taco","IceCream"=>"ice_cream","PopTarts"=>"pop_tart"}
    
    attributes.each do |attribute, element|
      message.send((attribute + '=').to_sym, hash_map[element])
    end
    

    或者像这样:

    class Example
      attr_reader :Pizza, :PastaBowl #...
    
      def initialize args
        args.each do |k, v|
          instance_variable_set("@#{k}", v) unless v.nil?
        end
      end
    end
    

    更多详情click here

    【讨论】:

    • 您可能应该添加一个if respond_to?("#{k}=") 以确保您尝试设置现有的设置器。
    【解决方案2】:

    我最终做了以下方法:

    attributes = Hash[]
    attributes["restaurant"] = tmp_basic_info.name
    attributes["menu_item"] = tmp_basic_info.item_name
    
    t.rows.each do |r|
      for i in 0..r.length-1
         attributes["other"] = t.other_information
         attributes[hash_map[t.combined_columns[i]] = r[i]
      end
      row = ImportMenuItem.new(attributes)
      row.save
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多