如何将控制器中的值解析回yaml?

时间:2017-05-10 14:05:05

标签: ruby-on-rails ruby forms

我的application.html.erb中有一个表单:

 <%=form_tag("/parse_input", method: "post") do %>
        <%= text_field(:ans, :field) %>
        <%= text_field(:ans1, :field) %>
        <%= text_field(:ans2, :field) %>
        <%= submit_tag("submit") %>
    <%end%>

    <%= @ans.to_s %>

在form_controller.rb中解析:

class FormController < ApplicationController
  def parse_input
    params[:ans].each do |value|
      render :template => "layouts/application.html.erb", :locals => {value => value.upcase}
    end
  end
end

我想将表单值写入YAML文件。我在application.html.erb中设置了一个虚函数,它可以从哈希中成功生成YAML。如何使用表单值生成YAML?

2 个答案:

答案 0 :(得分:2)

为简单起见,假设params包含:

params = {
  ans: 'foo'
}

使用:

require 'yaml'

File.write('foo.yaml', params.to_yaml)

运行文件后将包含:

---
:ans: foo

答案 1 :(得分:1)

使用Ruby File

在您的控制器File.open()操作 1 中添加parse_input

File.open(Rails.root.join('data', 'answers.yaml'), 'a') do |file|
  file << params.to_yaml
end

此代码将在answers.yaml目录 2 中创建/data文件(选中open选项here)并附加所有{{1} (以 yaml 格式)。

请注意,params会在params.to_yaml中包含所有参数,因此您的文件将与此类似:

params

因此,您可能希望在创建文件之前过滤--- !ruby/object:ActionController::Parameters parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess utf8: "✓" authenticity_token: fdUblOU+QL/daIdRoa94IbOjm0RWL/ugABsEYsdfem/Pt+N5hCSMQpfMVWanfqCHoX4WDPfTEUuVsNSJsnuvyQ== ans: !ruby/hash:ActiveSupport::HashWithIndifferentAccess field: answer1 ans1: !ruby/hash:ActiveSupport::HashWithIndifferentAccess field: answer2 ans2: !ruby/hash:ActiveSupport::HashWithIndifferentAccess field: answer3 commit: submit controller: form action: parse_input permitted: false ,并且您可以首先更改params标记的名称来完成此操作:

input

这将生成一个表单,<%=form_tag("/parse_input", method: "post") do %> <%= text_field(:answers, :ans1) %> <%= text_field(:answers, :ans2) %> <%= text_field(:answers, :ans3) %> <%= submit_tag("submit") %> <%end%> 个名称将在input中分组,例如,第一个输入answers将为name

现在,您只能使用answers[ans1]访问answers参数(这会过滤掉该组中的所有内容,例如params[:answers]commitcontroller等;);但我们仍需要更多过滤,因为action将输出:

params[:answers].to_yaml

因此,作为第二步,在致电--- !ruby/object:ActionController::Parameters parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess ans1: answer1 ans2: answer2 ans3: answer3 permitted: false 之前致电as_json;这会将to_yaml对象转换为ActionController::Parameters格式,删除额外的参数(例如jsonparameters),所以

permitted

将创建以下File.open(Rails.root.join('data', 'answers.yaml'), 'a') do |file| file << params[:answers].as_json.to_yaml end 文件;

answers.yaml

备注

1 如果在控制器中创建私有方法,并在操作中调用该方法,可能会更好。

2 应首先创建您选择的目录(示例中为--- ans1: answer1 ans2: answer2 ans3: answer3