【问题标题】:Mongoid Relational AssociationsMongoid 关系关联
【发布时间】:2011-01-27 03:23:48
【问题描述】:

我正在使用 rails3+mongoid+devise 创建一个应用程序。我有用户,每个用户都可以有约会,我想知道我是否应该在约会文档中显式存储一个 user_id 或者如何让 mongoid 通过定义的关系自动处理这个问题。

User 和 Appointment 模型如下

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

我想知道如何创建约会并将其与当前登录的用户关联(使用设计的 current_user)。

关于以下锻炼控制器的任何建议,特别是第 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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb devise mongoid


    【解决方案1】:

    首先,我相信Appointment 类的最后一行应该是referenced_in :user 而不是:person

    然后,您应该能够修复控制器的第 2 行,如下所示:

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

    保存后,current_user.appointments 应包含新约会。

    【讨论】:

    • 糟糕, :person 而不是 :user 是我的错字。但是,是的,它现在有效,非常棒。忘了你需要使用“appointments.new”而不是“appointment.new”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多