mongoid,形成建设者和关系

时间:2012-09-24 14:14:13

标签: ruby-on-rails ruby-on-rails-3 mongoid simple-form

我期待混合mongoid和simple_form的一些麻烦(我认为 - 同样的问题对于其他表单构建者来说是实际的)。我有一个关系的小形式,如

f.input :author, collection: User.all, as: :select

当我提交没有选择作者的表格时,我会看到像

这样的例外情况
NoMethodError in ExamplesController#update
undefined method `id' for "":String

太伤心了:(正如我所见 - simple_form提交“”(空字符串)但不是nil到控制器。当然 - 我可以从表单构建器验证每个参数,但我不确定它是不是很好的解决方案。可以你推荐我什么?

UPD (模型结构):

user.rb

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :examples, :inverse_of => :author
  has_many :examples, :inverse_of => :responsible_person
end

example.rb

class Example
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes

  field :title, type: String
  field :description, type: String

  belongs_to :author, :class_name => "User"
  belongs_to :responsible_person, :class_name => "User"

  validates_presence_of :title, :description, :author

  attr_accessible :title, :description, :author, :responsible_person

end

2 个答案:

答案 0 :(得分:4)

我在表单上直接使用author_id和responsible_person_id解决了这个问题,就像这样

= f.input :author_id, collection: User.all, as: :select
= f.input :responsible_person_id, collection: User.all, as: :select 

而不是

= f.input :author, collection: User.all, as: :select
= f.input :responsible_person, collection: User.all, as: :select

答案 1 :(得分:0)

试试这个

<%= f.association :author %>