2013年2月2日土曜日

mongoid on rails: diff with Railscast tutorial for mongoid >= 3.0.0

Problem

there is a mongoid great tutorial:
http://railscasts.com/episodes/238-mongoid

but this tutorial doesn't work for mongoid >= 3.0.0.


you might see some error messages like:

undefined method `key?' for nil:NilClass

undefined method `referenced_in' for Article:Class

undefined method `references_many' for Author:Class

undefined method `article_comments_path' for

No route matches [POST] "/articles/.../comments"


it seems that there was some changes its specification.




Solution

all you need to modify for suits 3.0.0 are bellow:

diff --git a/app/models/article.rb b/app/models/article.rb
index a00e637..386536a 100644
--- a/app/models/article.rb
+++ b/app/models/article.rb
@@ -5,5 +5,5 @@ class Article
   field :published_on, :type => Date
   validates_presence_of :name
   embeds_many :comments
-  referenced_in :author
+  belongs_to :author
 end
diff --git a/app/models/author.rb b/app/models/author.rb
index 7741009..e52989e 100644
--- a/app/models/author.rb
+++ b/app/models/author.rb
@@ -1,6 +1,6 @@
 class Author
   include Mongoid::Document
   field :name, type: String
-  key :name
-  references_many :articles
+  field :_id, type: String, default: ->{ name }
+  has_many :articles
 end
diff --git a/config/routes.rb b/config/routes.rb
index 31cc8de..45ac1c4 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -2,7 +2,9 @@ Mongoid01::Application.routes.draw do
   resources :authors
 
 
-  resources :articles
+  resources :articles do
+    resources :comments
+  end
 
   # The priority is based upon order of creation:
@@ -54,7 +56,7 @@ Mongoid01::Application.routes.draw do
 
   # You can have the root of your site routed with "root"
   # just remember to delete public/index.html.
-  # root :to => 'welcome#index'
+  root :to => 'articles#index'
 
   # See how all your routes lay out with "rake routes"

happy coding ! :)

0 件のコメント: