1

As mentioned on title, I made a Rails 4 app that contains

  • mongoid (5.1.3)
  • devise (4.2.0)
  • simple_form (3.2.1)

I set up my app with commands below:

rails g mongoid:config
rails g simple_form:install --bootstrap
rails g devise:install
rails g devise User
rails g scaffold post title content:text user:references

I add the code below in user.rb model file to make association between two models:

  embeds_many :posts

When I run app and create a user on it, then I visit http://localhost:3000/posts/new to create a new post, I got the error below:

Started GET "/posts/new" for 127.0.0.1 at 2016-07-29 19:54:21 +0300
Processing by PostsController#new as HTML
MONGODB | Adding localhost:27017 to the cluster.
MONGODB | localhost:27017 | mongoblog_development.find | STARTED | {"find"=>"users", "filter"=>{}}
MONGODB | localhost:27017 | mongoblog_development.find | SUCCEEDED | 0.0009257450000000001s
  Rendered posts/_form.html.erb (134.4ms)
  Rendered posts/new.html.erb within layouts/application (140.6ms)
Completed 500 Internal Server Error in 144ms

ActionView::Template::Error (undefined method `user_ids' for #<Post _id: 579b8a3d419a8f180afbb798, title: nil, content: nil>
Did you mean?  user?):
    4:   <div class="form-inputs">
    5:     <%= f.input :title %>
    6:     <%= f.input :content %>
    7:     <%= f.association :user %>
    8:   </div>
    9: 
   10:   <div class="form-actions">
  app/views/posts/_form.html.erb:7:in `block in _app_views_posts__form_html_erb__2731111319355307354_47423040086160'
  app/views/posts/_form.html.erb:1:in `_app_views_posts__form_html_erb__2731111319355307354_47423040086160'
  app/views/posts/new.html.erb:3:in `_app_views_posts_new_html_erb__3061427264044886497_70253725122920'

I searched it on search engine and here but there was nothing related with this issue. How can I fix it?

TEMPORARY SOLUTION:

Replacing embeds_many and embedded_in associations in model files with has_many and belongs_to makes the app work. By this replacement, it is possible to access Posts belongs to User or Users Post. I wonder whether it's possible to make association in first situation, using embeds_many and embedded_in.

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
  • this line causing the issue `<%= f.association :user %>` .. Rails is thinking or expecting the `user_id` column to be present in the `Post` model. because that is how Rails association works. But I never used Mongo, so not sure how this works in mongoid. – Arup Rakshit Jul 29 '16 at 17:19
  • Hi @ArupRakshit! I've created `user` and `post` instances manually and associated with each other properly. When I use `embeds_many` & `embedded_in` in models respectively, then I call `Post.first.user` on Rails console, I got `NoMethodError: undefined method `user' for nil:NilClass` error. But when I replace them with `has_many` & `belongs_to`, suprisingly got this one: `#` – ekremkaraca Jul 30 '16 at 07:57

0 Answers0