【问题标题】:How to iterate through Ruby/Rails relation如何遍历 Ruby/Rails 关系
【发布时间】:2013-03-06 08:31:50
【问题描述】:

我有一个模型 FacebookProfile,它包含 a、b 和 c 三列。

我通过这样做来调用这个对象:

@facebook_profile = FacebookProfile.find_by_facebook_id(1)

然后我可以访问 a、b 和 c 列的每个值

@facebook_profile.a # result: 1
@facebook_profile.b # result: 2
@facebook_profile.c # result: 3

如果我有一组项目 a、b 和 c,我如何在 @facebook_profile 上迭代调用这些项目?

我的最佳猜测:

my_array = ["a", "b", "c"]
for i in my_array
  puts @facebook_profile.i
end

预期输出:1、2、3

我已经看到了一种遍历所有列的方法,但是除了 a、b 和 c 之外,我还有其他列,所以我认为这不会奏效。

【问题讨论】:

    标签: ruby arrays ruby-on-rails-3 object iteration


    【解决方案1】:

    我认为你可以使用sendoperator 来做一些类似的事情

    my_array = ["a","b","c"]
    
    for i in my_array
      puts @facebook_profile.send(i.to_sym)
    end
    

    【讨论】:

    • 当我像这样实现这个时,我得到“意外的'=',期待keyword_end” => @facebook_profile.send(s.to_sym) = new_tags。知道为什么会这样吗?
    • 哦,偶然发现了一个修复:@facebook_profile.send(s + '=', new_tags) 这有点尴尬,但它会做。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    相关资源
    最近更新 更多