【问题标题】:Rails mongoid tri-model relationshipsRails mongoid 三模型关系
【发布时间】:2012-03-12 09:30:15
【问题描述】:

我在上面用蓝色描绘了这种关系,但是,它会提示许多错误,例如没有方法错误。

A 和 C 之间的嵌入关系(红色)可以吗?考虑到另外两个关系。

此外,在路由文件中,我应该将 B 嵌套在 A 中吗?

请指教,谢谢。

class Trip
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name
  key :name

  belongs_to :user
  has_many :logs
end

class Log
  include Mongoid::Document
  field :content
  validates_presence_of :content
  belongs_to :trip
  belongs_to :user
end

class User
  include Mongoid::Document
  has_many :trips
  has_many :logs
end

错误:

NoMethodError in Trips#show

Showing /home/jason/apps/app/views/trips/show.html.haml where line #17 raised:

undefined method `logs_path' for #<#<Class:0x9b8a14c>:0x9d3251c>

控制器:

class TripsController < ApplicationController
   def show
    @trip = Trip.find(params[:id])
    @log = Log.new
    @logmsg = @trip.logs
  end
end

class LogsController < ApplicationController

  def create
    @log = @trip.logs.build(params[:log])
    current_user.logs.build(params[:log])

    respond_to do |format|
      if @log.save
        format.html { redirect_to @log, notice: 'successfully created.' }
      else
        format.html { redirect_to trip_path(@trip) }
      end
    end
  end

  def destroy
    I want an ajax destroy here, as the logs will only be shown in the Trips show page.
  end
end

演出 - trips/show.html.haml:

= form_for @log do |f|
  .field
    = f.label :content
    = f.text_field :content
  .actions
    = f.submit 'Save'

以下是路由文件摘录:

App::Application.routes.draw do
  resources :trips do
    resources :logs
  end
end

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3.1 mongoid relationship


【解决方案1】:

不,您不能在ModalC 中嵌入ModalA,因为ModelB 将无法引用嵌入的对象。

嵌入式模型实际上是父文档中,而不是在单独的集合中。

【讨论】:

  • 但是我引用了蓝色手迹所描绘的模型,仍然不起作用。您能告诉我如何将它们三个联系起来吗?谢谢。
  • 如果您可以更新您的问题以包含您的模型代码和您遇到的确切错误,这将变得更加容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
相关资源
最近更新 更多