我怎样才能让钢轨自动填充动态生成的表单? [英] How can I get rails to automatically populate a dynamically generated form?

查看:112
本文介绍了我怎样才能让钢轨自动填充动态生成的表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个模型

  class A< ApplicationRecord 
serialize:vals,Array
end

存储一组值。我如何动态填充表单值列表?我的第一个猜测是写出

 <%= @ a.vals.each_with_index do | v,i | %GT; 
<%= f.text_field:hints%>
<%end%>

但是这给了我错误。

解决方案

提交此表格

 <%= form_for @a do | f | %GT; 
<%@ a.vals.each do | val | %GT;
<%= f.text_field:vals,value:val,multiple:true%>
<%end%>

<%= f.submit%>
<%end%>

传递a=> {vals=> [第一个,第二个,第三个]} 查看 A 的实例中的 vals ,而不是类 A $ b

关于 serialize 的注意事项(更多的评论说它看起来错了)我从来没有用过它, serialize:vals,Array 似乎对我有用

  A.create(vals:['hint 1','hint 2']); A.last.vals 
#(0.2ms)BEGIN
#SQL(0.4ms)INSERT INTO ... [[vals,--- \ n-hint 1 \\\
-提示2 \\\
] ...
#(0.6ms)COMMIT
#A Load(0.3ms)SELECTas。* FROMasORDER BYas。id DESC LIMIT $ 1 [[LIMIT,1]]
#=> [提示1,提示2]


Let's say I have a model

class A < ApplicationRecord
  serialize :vals, Array
end

which stores an array of values. How can I dynamically populate a list of form values? My first guess was to write

<%= @a.vals.each_with_index do |v, i| %>
  <%= f.text_field :hints %>
<% end %>

but this is giving me errors.

解决方案

Submitting this form

<%= form_for @a do |f| %>
  <% @a.vals.each do |val| %>
    <%= f.text_field :vals, value: val, multiple: true %>
  <% end %>

  <%= f.submit %>
<% end %>

passes "a"=>{"vals"=>["first", "second", "third"]} in the params to the controller.

As mentioned in the comments, you want to look at the vals from an instance of A not the class A.

Note about the serialize (more for the comments saying it looks wrong) I had never used it, that serialize :vals, Array seems to be working for me

A.create(vals: ['hint 1', 'hint 2']); A.last.vals
#   (0.2ms)  BEGIN
#   SQL (0.4ms)  INSERT INTO ... [["vals", "---\n- hint 1\n- hint 2\n"]...
#   (0.6ms)  COMMIT
#   A Load (0.3ms)  SELECT  "as".* FROM "as" ORDER BY "as"."id" DESC LIMIT $1  [["LIMIT", 1]]
# => ["hint 1", "hint 2"]

这篇关于我怎样才能让钢轨自动填充动态生成的表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆