Rails Mongoid时间戳似乎不起作用

时间:2014-03-04 22:26:50

标签: ruby-on-rails-4 timestamp mongoid

这是我的模型 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

时间戳* created_at *应该由Mongoid自动创建,但数据库中没有这样的属性Message.created_at。我不明白为什么。

embeds_many模型:

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

这就是我创建房间的方式:

  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

这是我创建消息的方式:

  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

我正在使用Rails 4.0.0和Mongoid 4.0.0.beta1。

1 个答案:

答案 0 :(得分:2)

尝试将Room类修改为

class Room
  ...
  embeds_many :messages, cascade_callbacks: true
  ...
end