1 | 1 |
new file mode 100644 |
... | ... |
@@ -0,0 +1,27 @@ |
0 |
+class History |
|
1 |
+ include Mongoid::Document |
|
2 |
+ |
|
3 |
+ field :me, type: String |
|
4 |
+ field :_with, type: String |
|
5 |
+ |
|
6 |
+ embeds_many :messages, cascade_callbacks: true |
|
7 |
+ accepts_nested_attributes_for :messages |
|
8 |
+ |
|
9 |
+ index({ me: 1, _with: 1 }, { unique: false }) |
|
10 |
+ |
|
11 |
+ def self.find_me_with(me, with) |
|
12 |
+ where(me: me, _with: with).limit(1).first |
|
13 |
+ end |
|
14 |
+ |
|
15 |
+ def self.save_message(me, from, message, chat_with, chat_id = nil) |
|
16 |
+ _with = chat_id.blank? ? chat_with : chat_id |
|
17 |
+ history = find_me_with(me, _with) |
|
18 |
+ |
|
19 |
+ history = History.new(me: me, _with: _with) if history.nil? |
|
20 |
+ |
|
21 |
+ record = Message.new(message: message, from: from) |
|
22 |
+ history.messages << record |
|
23 |
+ |
|
24 |
+ history.save |
|
25 |
+ end |
|
26 |
+end |