代码之家  ›  专栏  ›  技术社区  ›  rtacconi

ActiveRecord:在模型中更改和保存对象状态

  •  3
  • rtacconi  · 技术社区  · 14 年前

      def incoming_acceptation(incoming_code)
        if invite_code == incoming_code
          accepted = true
          self.save
          true
        else
          false
        end
      end
    

    但它并没有改变和保存接受为真,它仍然处于前一状态,为假。

    @i.incoming_acceptation(incoming_code) => true
    @i.accepted => false
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   jordinl    14 年前
    self.accepted = true
    
        2
  •  6
  •   Ariejan    14 年前

    我建议:

    def incoming_acceptation(incoming_code)
      update_attribute(:accepted, true) if invite_code == incoming_code
    end
    

    update_attribute 将更改并保存该属性。还有 update_attributes (注意 s )接受哈希以同时更改多个属性的:

    @obj.update_attributes(:accepted => true, :accepted_at => Time.now)
    

    注: 更新属性 true 当更改和保存成功时,就像在您的示例中一样。