如何有效地在同一表的两个实例之间交换值

时间:2018-06-28 10:31:02

标签: ruby-on-rails ruby

我有两个Book实例,我想在两个sequence之间交换books列值

## Original values
# book_1.sequence = 10  
# book_2.sequence = 15

book_id = [1,2]

book_1 = Book.find(book_id.first)
book_2 = Book.find(book_id.second)

book_1_sequence = book_1.sequence
book_2_sequence = book_2.sequence

book_1.update_attributes!(sequence: book_2_sequence)
book_2.update_attributes!(sequence: book_1_sequence)

程序执行后:

book_1.sequence = 15
            book_2.sequence = 10

这可以解决问题,但这很简单,还有更好的方法吗?整洁高效

3 个答案:

答案 0 :(得分:0)

至少可以减少一行代码:

book_1.sequence = 10  
book_2.sequence = 15

book_id = [1,2]

book_1, book_2 = Book.find(book_ids)

book_1_sequence = book_1.sequence

book_1.update_attributes!(sequence: book_2.sequence)
book_2.update_attributes!(sequence: book_1_sequence)

根据Robbert van ELk的建议进行了更新。

答案 1 :(得分:0)

另一种方法:

# Original values
book_1.sequence
 => 10

book_2.sequence
 => 15

book_ids = [1,2]

# Fetch all the books in single query
book_1, book_2 = Book.find(book_ids)

book_1.sequence, book_2.sequence = book_2.sequence, book_1.sequence
[book_1, book_2].each(&:save!)

答案 2 :(得分:0)

用红宝石换行

# Original values
# book_1.sequence = 10  
# book_2.sequence = 15

book_id = [1,2]

book_1, book_2 = Book.find(book_ids)

book_1.sequence, book_2.sequence = book_2.sequence, book_1.sequence
book_1.save; book_2.save

甚至更短(不推荐,因为它很混乱,绝对不是整洁和不直观的):

Book.find(book_ids).tap { |book_1, book_2| book_1.sequence, book_2.sequence = book_2.sequence, book_1.sequence }.map &:save

#tap 产生 self in块,它映射到book_1book_2,交换序列值并返回 books 的顺序相同,然后save保存它。