gpt4 book ai didi

ruby-on-rails - mongoid,表单构建器和关系

转载 作者:行者123 更新时间:2023-12-04 06:11:43 25 4
gpt4 key购买 nike

我预计混合 mongoid 和 simple_form 会遇到一些麻烦(我认为 - 对于其他表单构建器来说,同样的问题是实际的)。我有一个带有关系的小表格,比如

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

当我提交没有选择作者的表单时,我看到类似的异常

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

太伤心了 :( 如我所见 - simple_form 向 Controller 提交“”(空字符串)但不是 nil。当然 - 我可以从表单生成器验证每个参数,但我不确定它是否是好的解决方案。可以你推荐我一些东西?

UPD(模型结构):

用户.rb

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

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

例子.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

最佳答案

我已经通过在表单上直接使用 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

关于ruby-on-rails - mongoid,表单构建器和关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12566841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com