Reputation: 841
Here is my model message.rb:
class Message
include Mongoid::Document
include Mongoid::Timestamps::Created
embedded_in :room
field :content
field :user_id # That's the guest_id; room_id if it's a room's owner message.
end
The timestamp *created_at* supposed to be automatically created by the Mongoid, but there is no such attribute Message.created_at in the database. I can't understand why.
The embeds_many model:
class Room
include Mongoid::Document
include ActiveModel::SecurePassword
embeds_one :guest
embeds_many :messages
has_secure_password
field :password_digest
field :owner_name
field :url
end
This is how I create the Room:
def create
@room = Room.new(room_params)
@room.password_confirmation = @room.password # Easy way to bypass the has_secure_password confirmation.
@room.url = generate_url
respond_to do |format|
if @room.save
session[@room.id.to_s.to_sym] = true
format.html { redirect_to "/chat/" + @room.url, notice: 'Room was successfully created.' }
format.json { render action: 'show', status: :created, location: @room }
else
format.html { render action: 'new' }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end
This is how I create the Messages:
def write_message
@room = Room.find(params[:id])
@room.messages.build(content: params[:message], user_id: params[:user_id])
if @room.save
render json: true
else
render json: @room.errors, status: :unprocessable_entity
end
end
I'm using Rails 4.0.0, and Mongoid 4.0.0.beta1.
Upvotes: 0
Views: 1481
Reputation: 8055
try modifying the Room class to be
class Room
...
embeds_many :messages, cascade_callbacks: true
...
end
Upvotes: 2