Alexey Poimtsev
Alexey Poimtsev

Reputation: 2847

mongoid, form builders and relations

i'm expecting some troubles with mixing mongoid and simple_form (i think - the same problem is actual for other form builders). I have a small form with relations, something like

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

and when i submit form with no author selected i see exception like

NoMethodError in ExamplesController#update
undefined method `id' for "":String

So sad :( as i see - simple_form submits "" (empty string) but not nil to controller. Of course - i can validate each param from form builder, but i'm not sure that it is good solution. Can you recommend me something?

UPD (Models structure):

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

Upvotes: 3

Views: 1244

Answers (2)

Alexey Poimtsev
Alexey Poimtsev

Reputation: 2847

I've solved this problem with direct use author_id and responsible_person_id on form, like this

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

instead of

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

Upvotes: 4

abhas
abhas

Reputation: 5213

try this

<%= f.association :author %>

Upvotes: 0

Related Questions