我试图在rails 4中使用“外键”,embedded_in和embeds_many的替代方法。我确信有一种方法可以解决这个问题,它对我来说目前为止还有意义Mongoid/Rails 4找不到文档错误
我的模型:
class Line
include Mongoid::Document
include Mongoid::Timestamps
embeds_many :stations
field :line, type: String
index({ starred: 1 })
end
class Station
include Mongoid::Document
include Mongoid::Timestamps
has_many :routes
embedded_in :line, inverse_of: :stations
field :name, type: String
end
现在我能够创建一个嵌套的途径,如: http://localhost:3000/lines/:line_id/stations 有:
Rails.application.routes.draw do
resources :lines do
resources :stations
end
resources :routes
root 'lines#index'
end
我的电台控制器:
class StationsController < ApplicationController
before_action :load_line
before_action :set_station, only: [:show, :edit, :update, :destroy]
# GET /stations
# GET /stations.json
def index
@stations = @line.stations
end
# GET /stations/1
# GET /stations/1.json
def show
end
# GET /stations/new
def new
@station = @line.stations.build
end
# GET /stations/1/edit
def edit
end
# POST /stations
# POST /stations.json
def create
@station = @line.stations.build(station_params)
respond_to do |format|
if @station.save
format.html { redirect_to @station, notice: 'Station was successfully created.' }
format.json { render :show, status: :created, location: @station }
else
format.html { render :new }
format.json { render json: @station.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /stations/1
# PATCH/PUT /stations/1.json
def update
respond_to do |format|
if @station.update_attributes(station_params)
format.html { redirect_to @station, notice: 'Station was successfully updated.' }
format.json { render :show, status: :ok, location: @station }
else
format.html { render :edit }
format.json { render json: @station.errors, status: :unprocessable_entity }
end
end
end
# DELETE /stations/1
# DELETE /stations/1.json
def destroy
@station.destroy
respond_to do |format|
format.html { redirect_to stations_url, notice: 'Station was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_station
@station = @line.stations.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def station_params
params.require(:station).permit(:name)
end
def load_line
@line = Line.find(params[:line_id])
end
end
但是当我参观路线,我得到:
消息:文件(S)未找到班线有ID(S):line_id。摘要:使用id或id数组调用Line.find时,每个参数必须与数据库中的文档匹配,否则将引发此错误。搜索的是id(s)::line_id ...(总共1个),但没有找到以下id::line_id。解决方案:搜索数据库中的id或将Mongoid.raise_not_found_error配置选项设置为false,这将导致返回nil而不是在搜索单个id时引发此错误,或在搜索时仅返回匹配的文档倍数。
请将您的routes.rb文件的相关部分贴出。 – toddmetheny
完成后,我更新了该文章 – Mohammed
*请确保您的文件正确缩进*。看看routes.rb,你仍然可以正确地掌握那几个吗?我需要两眼,因为我的头脑首先告诉我你在那里有一个错误。 –