【问题标题】:Ruby on Rails - how to loop through object and reset valuesRuby on Rails - 如何遍历对象和重置值
【发布时间】:2012-04-30 14:56:27
【问题描述】:

我正在遍历一个对象列表并更改一些值。当我将值输出到记录器中时,我会看到更改后的值,但是在结果页面上时,更改不会被保存。

这是我的循环:

@dis.each do |d|
  temp = d.notes.inspect

  #Now check the length of the temp variable
  temp.length > 25 ? temp = temp[0,25] :  nil

  d.notes = temp
end

如何更改它以便将 temp 的新值保存在 @dis 对象中?

谢谢!

【问题讨论】:

  • @fl00r 视图有点意大利面,但为什么循环不够代码?不能只用新值重置对象吗?

标签: ruby-on-rails ruby


【解决方案1】:

你可以使用collect获得你想要的结果!或地图!修改 就地数组:

https://stackoverflow.com/a/5646754/643500

x = %w(hello there world)
x.collect! { |element|
  (element == "hello") ? "hi" : element
}
puts x

编辑:

所以你的代码看起来像

@dis.collect! do |d|
  temp = d.notes.inspect

  #Now check the length of the temp variable
  temp.length > 25 ? temp = temp[0,25] : temp = nil

  d.notes = temp
end

编辑:

在这里工作的完整代码。确保你有带有 getter 和 setter 的 :notes。了解 cattr_accessor、attr_accessor 和 attr_accessible

class TestClass
  @note
  def initialize note
    @note = note
  end
  def get_note
    @note
  end
  def set_note note
    @note = note
  end
end

@dis = Array.new
@dis << TestClass.new("yo yo")
@dis << TestClass.new("1 2 3 4 5 6 7 8 9 10 6 7 8 9 10 6")
@dis << TestClass.new("a b c")

@dis.collect! do |d|
  temp = d.get_note.inspect

  #Now check the length of the temp variable
  d.get_note.inspect.length > 25 ? d.set_note(temp[0,25]) : d.set_note(nil)

end


puts "#{@dis}"

【讨论】:

  • 我对一些红宝石技术有点陌生。在这里,我只是循环一个对象。如何更改单个字段并在对象列表中重置该对象?
  • 我的意思是……“puts x”能做到这一点吗?
  • puts x #just 证明它更新了值。所以,它只是打印它。关键是 collect 和 map 迭代实际对象,因此允许我们更新它。
  • 但我不确定这在我的情况下如何工作,因为我需要在对象中替换它。知道我应该尝试什么吗?
  • 谢谢 - 我尝试了你的建议,但它并没有最终将价值传播到视图......我会继续研究。
【解决方案2】:

您似乎正在尝试截断 notes 属性。

这就够了:

@dis.each do |d|
  d.notes = d.notes.inspect[0,25]
end

由于赋值,这将改变数组内的对象,但不会改变数组对象本身。 map!collect!(它们是别名)将更改数组本身,但不会更改其中的对象。 mapcollect 将一起返回一个新数组。

如果你的问题是它没有保存到数据库中,那么你应该在某处放一个d.save

如果只是为了呈现,为什么不在视图中呈现的时候截断值呢?

<%= truncate d.notes, :length => 25 %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2012-07-14
    相关资源
    最近更新 更多