Calling Document.find with nil is invalid MongoId in Rails 4

佐手、 提交于 2019-12-12 01:54:14

问题


There are three models in my app: User, Subject and Note.

I've already embedded Note model into Subject model and it works. Now when I try to embed Subject into User always get Mongoid::Errors::InvalidFind coming from this line of code:

In the method one should define to use in before_action at the beginning of the controller

@user = User.find(params[:user_id])

subjects_controller

class SubjectsController < ApplicationController
#before_filter :authenticate_user!, only: [:index]
before_action :set_subject, only: [:show, :edit, :update, :destroy]
before_action :load_user

def index
    @subjects = @user.subjects
end

def new
    @subject = @user.subjects.build
end

 def show

 end

def create
    @subject = @user.subjects.create(subject_params)

    respond_to do |format|
         if @subject.save
            format.html {redirect_to subject_path(@subject)}
        else
            format.html {render 'new'}
        end
    end
 end

 def update
    if @subject.update(subject_params)
        redirect_to @subject
    else
        render 'edit'
    end


 end

def delete

end

private

     def subject_params
        params.require(:subject).permit(:name)
     end

    def set_subject
        @subject = @user.subject.find(params[:id])
    end

    def load_user
        @user = User.find(params[:user_id])
    end
end

Routes

resources :users do
  resources :subjects do
    resources :notes
  end
end

Right now I'm pretty stuck here because haven't found a way to work this around, hope someone around can give a hand.


回答1:


Take into account this RoR best practice "Resources should never be nested more than 1 level deep." http://guides.rubyonrails.org/routing.html#nested-resources

A collection may need to be scoped by its parent, but a specific member can always be accessed directly by an id, and shouldn’t need scoping (unless the id is not unique, for some reason). http://weblog.jamisbuck.org/2007/2/5/nesting-resources



来源:https://stackoverflow.com/questions/27371085/calling-document-find-with-nil-is-invalid-mongoid-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!