Module: ActiveRecordExtras::Relation::ClassMethods

Defined in:
lib/monkey_patch_happy/active_record_extras.rb

Instance Method Summary collapse

Instance Method Details

#create_or_update(attributes, &block) ⇒ Object



7
8
9
10
11
# File 'lib/monkey_patch_happy/active_record_extras.rb', line 7

def create_or_update(attributes, &block)
  new_or_assign(attributes) do |obj|
    block.call(obj) if block_given?
  end
end

#new_or_assign(attributes) {|obj| ... } ⇒ Object

Yields:

  • (obj)


14
15
16
17
18
19
20
# File 'lib/monkey_patch_happy/active_record_extras.rb', line 14

def new_or_assign(attributes)
  obj = where(attributes).last || new(attributes) #不存在就创建。
  # obj.assign_attributes(attributes)
  yield obj
  obj.updated_at = Time.new
  obj.save
end