如何将 Rails 3 表单参数传递到数组中?

发布于 2024-10-09 17:26:02 字数 715 浏览 0 评论 0原文

我有一个嵌套表单(在相应模型中使用accepts_nested_attributes_for):

<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>  
   <%= f.fields_for :service do |s| %>  
       <%= s.text_field :name %>  
       <%= s.text_field :name %> 
       <%= s.text_field :name %>  
       <%= s.text_field :name %>  
   <% end %>  
<% end %>   

如果我只有一个 s.text_field,则效果很好。但是一旦我添加额外的文本字段,它就无法正常运行。如果你看一下源代码,六个人的 id 和 name 都是一样的?

如何将这些参数放入数组中? [这样我就可以像这样隔离它们:]

service1 = Service.named(params[:technician][:service][1][:name])  

(我已经尝试过railscasts第192集描述的方法,但它也不起作用)。

I have a nested form (using accepts_nested_attributes_for in respective models):

<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>  
   <%= f.fields_for :service do |s| %>  
       <%= s.text_field :name %>  
       <%= s.text_field :name %> 
       <%= s.text_field :name %>  
       <%= s.text_field :name %>  
   <% end %>  
<% end %>   

This works fine if I only have one s.text_field. But once I add additional text_fields, it doesn't run properly. If you look at the source code, the id and name are the same for all six?

How do I put these params into an array? [so that I can isolate them like this:]

service1 = Service.named(params[:technician][:service][1][:name])  

(I've tried the method described on railscasts episode 192, but it didn't work either).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不离久伴 2024-10-16 17:26:02

经过几个小时的反复试验,我已经破解了一些有效的方法(但是如果您知道更好、更雄辩的方法,请告诉我):

in view:

<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>  
  <% for @i in 1..6 do %>  
    <%= f.fields_for "services[#{@i}]" do |s| %>  
    <% end %>  
  <% end %>  
<% end %>  

in control:

 for i in 1..6 do  
        @service = Service.named(params[:technician][:services][i.to_s][:name]).first  
 end  

确保将 i 转换为 string

After hours of trial and error, I've hacked something that works (but please let me know if you know a better, more eloquent way):

in view:

<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>  
  <% for @i in 1..6 do %>  
    <%= f.fields_for "services[#{@i}]" do |s| %>  
    <% end %>  
  <% end %>  
<% end %>  

in controller:

 for i in 1..6 do  
        @service = Service.named(params[:technician][:services][i.to_s][:name]).first  
 end  

make sure you turn i into string

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文