Rails + MongoID + Simple Form in association: unde

2019-09-09 09:10发布

问题:

I have the following models which basically refer to Lessons and Categories. Each lesson can have one category, and each category is embedded in a lesson.

class Lesson
  include Mongoid::Document

  field :title, :type => String
  field :category, :type => String
  field :price, :type => Integer
  field :description, :type => String
  field :user_id, :type => String


  validates_presence_of :title
  validates_presence_of :category
  validates_presence_of :price
  validates_presence_of :user_id

  validates_numericality_of :price

  attr_accessible :title, :category, :description, :price

  embeds_one :category
end


class Category
  include Mongoid::Document
  field :name, type: String

  embedded_in :lesson
end

And I have a form like this:

<%= simple_form_for @lesson, :html => { :class => 'well' } do |lesson_form| %>
<% if lesson_form.error_notification %>
    <div class="alert alert-error fade in">
      <a class="close" data-dismiss="alert" href="#">&times;</a>
      <%= lesson_form.error_notification %>
    </div>
<% end %>
  <%= lesson_form.input :title %>
  <%= lesson_form.input :category %>
  <%= lesson_form.input :description %>
  <%= lesson_form.input :price %>
  <%= lesson_form.association :category %>
  <%= lesson_form.button :submit, :label => 'Create', :class => 'btn btn-primary btn-large' %>
<% end -%>

When trying to render that form, I get this error:

undefined method `options' for #<Mongoid::Relations::Metadata:0x000000049dc958>

Any thoughts how can I show the categories names in that form?

EDIT:

I have changed this line: <%= lesson_form.association :category %>

For this one: <%= lesson_form.input :category, :collection => Category.all %>

But when trying to load the form I get:

Access to the collection for Category is not allowed since it is an embedded document, please access a collection from the root document.

回答1:

Unfortunately it appears SimpleForm doesn't support ORMs other than ActiveRecord (see this issue for example). Sorry this isn't a very good 'answer' to your question :/