【问题标题】:Move one object in collection of objects in rails在rails中的对象集合中移动一个对象
【发布时间】:2016-06-01 00:48:21
【问题描述】:

这是场景,我有这些对象。假设这是User

对象来自:

@user = User.all

用户对象

[<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]

如何向上移动一个对象,例如我想移动User.id == 2?我想要的结果如下所示。

[<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]

【问题讨论】:

  • 您想要ActiveRecord Relation Object 中的结果还是将其转换为Array 可以?
  • 我已经解决了这个问题。我在下面发布了我的答案。

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


【解决方案1】:

我已经得到了答案。这是我为解决上述问题所做的工作。

@users = User.all
user_ids = User.pluck(:id)
user_ids.delete(2)
new_user_ids = [2]

user_ids.each do |id|
  new_user_ids << id
end

@users.sort_by { |user| new_user_ids.index(user.id) }

这很完美!

【讨论】:

    【解决方案2】:

    我们也可以这样做:

    向 Array 添加一个新方法。 lib/rails_extensions.rb

    class Array
    
      def swap!(a, b = a - 1)
               self[a], self[b] = self[b], self[a]
          self
      end
    
    end
    

    然后在 config/environment.rb 中添加这个

    require 'rails_extensions'
    

    所以我们可以对数组使用swap! 方法,它会将对象与之前的对象交换。我们可以这样做:

    @users = User.all #[<#User id: 1>, <#User id: 2>]
    user_id = @users.rindex {|user| user.id == 2}
    @users = @users.swap!(user_id) #[<#User id: 2>, <#User id: 1>]
    

    【讨论】:

    • 您只是在交换对象。而且您的代码不灵活。一个对象中只有 2 个。如果我有超过100个怎么办?你的意思是我修改了swap!方法?我下面的回答就够了。
    • 您的问题是关于向上移动一个对象?好吧,如果您想要更大的灵活性,为什么不将 arg b = a - 1 更改为 b,这样我们就可以切换到我们想要的任何索引?
    【解决方案3】:

    这也太丑了吧?

    hash = [{ id: 1}, {id: 2}, {id: 3}]
    hash.unshift(hash.delete(hash.select {|h| h[:id] == 2 }.first))
    => [{:id=>2}, {:id=>1}, {:id=>3}]
    

    【讨论】:

    • 不排序 id,它是对象集合中的整个 User 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多