Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将字符串值解释为ruby方法_Ruby On Rails_Ruby_Forms_Form For - Fatal编程技术网

Ruby on rails 将字符串值解释为ruby方法

Ruby on rails 将字符串值解释为ruby方法,ruby-on-rails,ruby,forms,form-for,Ruby On Rails,Ruby,Forms,Form For,我有一个FormQuestion模型,它将标签的表单_存储为字符串。 我希望有如下内容: <%= form_for(application_form) do |f| %> <% FormQuestion.all.each do |q| %> <%= q.input %> #where q.input = "f.text_field :name" <% end %> <% end %> #其中q.input=“f.t

我有一个FormQuestion模型,它将标签的表单_存储为字符串。 我希望有如下内容:

<%= form_for(application_form) do |f| %>
  <% FormQuestion.all.each do |q| %>
    <%= q.input %>  #where q.input = "f.text_field :name"
  <% end %>
<% end %>

#其中q.input=“f.text\u字段:名称”
如何将q.input返回的字符串解释为ruby标记的形式_,而不是简单地打印为页面上的文本

编辑:
eval(q.input)
,但我正在寻找一种更安全的替代方法

您可以使用以下方法:

<%= form_for(application_form) do |f| %>
  <% FormQuestion.all.each do |q| %>
    <%= f.send(q.input) %>  #where q.input = "f.text_field :name"
  <% end %>
<% end %>

#其中q.input=“f.text\u字段:名称”

我将其更改为:

<%= form_for(application_form) do |f| %>
  <% FormQuestion.all.each do |q| %>
    <% f.send q.type, q.name %>  #where q.type = :text_field and q.name = :name
   <% end %>
<% end %>

#其中q.type=:text_字段和q.name=:name
否则:

<%= form_for(application_form) do |f| %>
  <% FormQuestion.all.each do |q| %>
    <%= raw q.as_html %>  # where q.as_html = "<input name="name"></input>"
  <% end %>
<% end %>

#其中q.as_html=“”

试试
@NoamHacker已经试过了。它只打印可能应该是
f.send(q.input)
的字符串。也可以尝试
public\u send
,因为
send
也可以访问私有方法。但这仍然不是一个完整的答案,因为上面指出@mu太短了。如果
q.input
是一个数组,那么应该是
f.send(*q.input)
。“未定义的方法`f.text\u字段:name'”当使用f.send时,我得到错误:
“未定义的方法”:text\u字段'代表#你是指?text\u字段“
。对于
:name
,我得到了相同的错误。如果删除冒号,则页面上不会显示任何内容。我的意思是使用符号,即,
:text\u field
,尽管可以使用字符串(“text\u field”)。换言之,以下各项大致相当<代码>,
我知道我也应该写
而不是