【问题标题】:Trouble with setting attributes设置属性有问题
【发布时间】:2011-01-21 01:59:46
【问题描述】:

我有一个项目ActiveRecords,我正在尝试使用一个块为每个项目设置一个默认值(“测试项目”)。
在这个表达式中:

list = {"type1", "type2", "type3", "type4", "..."}
list.each { |name| @item.attributes["#{name}"] = "Test item"] }

值未设置。

我必须使用@item.attributes["#{name}"] 进行插值,因为我不能对每个项目都这样做:

@item.tipe1 = "Test item"

那么,第一个语句会发生什么?为什么?如果我想做的事不能那样做,我怎么能做同样的事?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 block proc-object


    【解决方案1】:

    赋值@items.attributes["#{name}"] = "Test item"] 不起作用,因为每次调用attributes 方法都会返回一个新的Hash 对象。因此,您并没有像您想象的那样更改 @items' 对象的值。相反,您正在更改已返回的新 Hash 的值。并且每次迭代后这个 Hash 都会丢失(当然,当 each 块完成时)。

    一种可能的解决方案是使用@items' 属性的键创建一个新哈希,并通过attributes= 方法分配它。

    h = Hash.new
    
    # this creates a new hash object based on @items.attributes
    # with all values set to "Test Item"
    @items.attributes.each { |key, value| h[key] = "Test Item" }
    
    @items.attributes = h
    

    【讨论】:

      【解决方案2】:

      您可以为此目的使用 send 方法。可能是这样的:

      list = {"type1", "type2", "type3", "type4", "..."}
      list.each { |name| @item.send("#{name}=", "Test item") }
      

      【讨论】:

        【解决方案3】:

        我认为问题在于您只更改了返回的属性哈希,而不是 ActiveRecord 对象。

        您需要执行以下操作:

        # make hash h
        @items.attributes = h
        

        按照您的示例,可能类似于:

        @items.attributes = %w{type1 type2 type3 type4}.inject({}) { |m, e| m[e] = 'Test item'; m }
        

        顺便说一句,"#{e}" 与字符串表达式 e 或任何类型:e.to_s 相同。第二个例子,也许更容易阅读:

        a = %w{type1 type2 type3 type4}
        h = {}
        a.each { |name| h[name] = 'test item' }
        @items.attributes = h
        

        使用attributes= 方法可能适用于哈希常量,例如:

        @items.attributes = { :field => 'value', :anotherfield => 'value' }
        

        对于完全生成的属性,您可以接受DanneManne's 建议并使用发送。

        【讨论】:

        • 我认为你的回答是最好的,但丹尼尔的描述让我更容易理解我的问题是什么。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多