轨道循环遍历表单中的必需属性



在我的Ruby on Rails项目中,我有一个名为Node的模块。在该模块中,我有不同的类,例如playbackifhangup等。它们是使用Node::Playback,例如。其中每个类都有不同的必需属性。节点具有以下声明作为其一部分:

class Node < ActiveRecord::Base
...Other irrelevant code
class << self
attr_accessor :required_attrs
attr_accessor :optional_attrs
def acts_as_node required_attrs=[], optional_attrs=[]
@required_attrs = required_attrs
@optional_attrs = optional_attrs
(required_attrs + optional_attrs).each do |attr|
attr_accessor attr
end
required_attrs.each do |attr|
validates attr, presence: true
end
end
end
end

例如,声明为class Node::Playbackplayback在其模型中具有以下内容:

class Node::Playback < Node
acts_as_node [ :body, :author ]
end

在创建播放节点的视图中,我想遍历所有必需的属性,即[:body, :author].重要的是我动态执行此操作,而不是硬编码,因为 Node 有许多不同的类,而不仅仅是播放。

= form_for([@callflow, @new_node]) do |f|
h2 | Fill All Required Attributes Below
- @node_type.required_attrs.each do |ra|
.form-group
= f.label ra
= f.text_area(ra)
h2 | Fill Optional Attributes Below
- @node_type.optional_attrs.each do |oa|
.form-group
= f.label oa
/= f.text_area oa
.form-group
= f.submit class: 'btn btn-success'

在上面的代码中,当我在控制器中对它进行错误处理时,@node_type.required_attrs 返回了[:body, :author]。我还检查了数组中的元素是否属于"符号"类。@new_node是使用Node.new(callflow: @callflow)创建的,@node_type是使用"Node::Playback".constantize

创建的f.label ra会在我的视图中放置正确的标签(即,当我注释掉它下面的行时,在我的表单中正确放置一个标签(。 但是,当我f.text_area raf.text_area(ra)时,它会说undefined method body' for #<Node:0x00007f271df3bc18>

有什么建议吗?

@new_node似乎是Node的一个实例。 我没有看到@node_type的定义,但根据错误,我假设它是一个Node::Playback实例。

Node实例将不具有Node::Playback的必需属性,因此当您要求表单呈现器f(表示Node实例(呈现Node::Playback实例的必需属性ra时,您会收到错误。

试试这个:

= form_for([@callflow, @new_node]) do |f|
h2 | Fill All Required Attributes Below
- f.object.required_attrs.each do |ra|
.form-group
= f.label ra
= f.text_area(ra)

然后确保@new_node实例的类型合适(例如Node::Playback(

最新更新