Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 519
Alexey Poimtsev Avatar asked Jul 10 '26 19:07

Alexey Poimtsev


1 Answers

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
like image 107
Alexey Poimtsev Avatar answered Jul 13 '26 16:07

Alexey Poimtsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!