簡體   English   中英

蒙古族關系協會

[英]Mongoid Relational Associations

我正在使用rails3 + mongoid + devise創建一個應用程序。 我有用戶,每個用戶都可以有附件,我想知道我是否應該在約會文檔中顯式存儲一個user_id,或者如何讓mongoid使用定義的關系自動處理此問題。

用戶和約會模型如下

class User
  include Mongoid::Document
  devise: database_authenticable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  field :username
  validates_presence_of :username
  validates_uniqueness_of :name, :email, :case_sensitive => false
  attr_accessible :name, :email, :password, :password_confirmation

  references_many :appointments
end

class Appointment
  include Mongoid::Document

  field :date, :type => Date, :default => Date.today
  referenced_in :user
end

我想知道如何創建約會並將其與當前登錄用戶(使用devise的current_user)相關聯。

關於以下training_controller的任何建議,特別是第2行?

def create
  @appointment = current_user.Appointment.new(params[:appointment])
  if @appointment.save
    redirect_to(:action => 'show', :id => @appointment._id)
  else
    render('edit')
  end
end

首先,我相信您在Appointment類的最后一行應該說referenced_in :user而不是:person

然后,您應該能夠如下修復控制器的第2行:

@appointment = current_user.appointments.new(params[:appointment])

保存后, current_user.appointments應包含新約會。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM