我有两个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
这可以解决问题,但这很简单,还有更好的方法吗?整洁高效
答案 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_1
和book_2
,交换序列值并返回 books 的顺序相同,然后save
保存它。