【问题标题】:How to use the select_tag helper in a nested form?如何以嵌套形式使用 select_tag 助手?
【发布时间】:2010-07-10 21:18:24
【问题描述】:

更新:底部的解决方案

我希望其他人已经花了一些时间来解决同样的问题...我正在 Rails 应用程序中构建一个地址簿,并且我有一个 Person 模型和一个 Email 模型。 Person has_many Emails,并且 Person Accepted_nested_attributes_for :emails。

这一切都很完美——我有一个嵌套表单,我可以使用它在我的表单中添加和删除电子邮件及其属性(使用类似于 Railscasts 196-7 (here) 的方法)。提交表单会创建具有所有正确关联的人员以及电子邮件。

问题是,就目前而言,我无法找到一种方法来使用嵌套电子邮件模型上的选择标签,让用户为该电子邮件选择一种类型(例如工作、家庭、其他)。因此,按照我现在的方式编辑 Person 模型,没有简单的方法可以选择存储在 rails 模型中的属性。

这是我现在拥有的:

<%= form_for(@source) do |f| %> 
<% f.fields_for :emails do |builder| %>  
. . . 
<%= builder.text_field :address, :size => 15 %>



<%= render :partial => 'email_select_1' %>0<%= render :partial => 'email_select_2' %>0<%= render :partial => 'email_select_3' %>

注意:以上是允许我稍后在 javascript 中使用相同的代码片段设置 ID 的一种 hacky 方式。部分吐出硬编码的选择和选项,在本例中为“0”,但在 javascript 中我可以将其更改为唯一的:

<select id="person_emails_attributes_0_kind" name="person[emails_attributes][0][kind]"><option value="work">work</option><option value="home">home</option><option value="other">other</option></select>

然后其余的看起来像这样(缩写):

. . .
<% end %>  
. . .
<!-- more form stuff, actions, etc... -->
. . . 
<% end %>

有没有办法为此使用 select_tag 帮助程序,并替换我的 hacky-hard-coded 选择?如果没有,对编写我自己的辅助方法有什么建议吗?

提前致谢!

更新:感谢 Geoff 提供的解决方案。对于后人来说,最重要的是使用select,而不是select_tag。然后你可以这样做:

<%= builder.select :kind, [['work', 'work'], ['home', 'home'], ['other', 'other']]%>

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您只需要将 formbuilder 变量传递给部分。你可以通过像这样编码你的部分来做到这一点:

    <%= form_for(@source) do |f| %> 
      <% f.fields_for :emails do |builder| %>  
      . . . 
      <%= builder.text_field :address, :size => 15 %>
        <%= render :partial => 'email_select_1', :locals => {:builder => builder} %>
      <% end %>
    <% end %>
    

    然后你会使用你的部分:

    <%= builder.select :kind %>
    

    就好像它在 fields_for 块内一样。

    希望这会有所帮助!

    【讨论】:

    • 在测试中,我收到此错误:未定义方法 `select_tag' for #<:helpers::formbuilder:0x1343deb38> 有什么想法吗?
    • 这是builder.select对此感到抱歉...修复了我的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多