【问题标题】:How do I use a form to fill a serialized array in a Rails 4 model?如何使用表单填充 Rails 4 模型中的序列化数组?
【发布时间】:2016-03-14 05:28:00
【问题描述】:

我正在使用form_for 创建新的Records。每条记录都有一个主照片 url :photo 和三个可选的照片 url,我将它们存储在一个序列化数组中,other_photos

在我的表单中,我希望用户可以选择添加最多三个额外的照片网址,这些网址将存储在 other_photos[0]other_photos[1]other_photos[2]

我将列添加到数据库中,将serialize :other_photos, Array 添加到模型中,并允许强参数:other_photos => []

如何在我的表单中处理这个问题?现在,我将这张照片作为我的主要照片:

<%= form_for @record do |r| %>
    ...
    <%= label_tag :name, "IMAGE URL:", class: "login-label" %>
    <%= r.text_field :photo, size: 50 %>

如何设置other_photos 的参数?这不起作用:

    <%= r.text_field :other_photos[0], size: 50 %>

【问题讨论】:

    标签: ruby-on-rails arrays forms serialization


    【解决方案1】:

    我让它工作了。我仍然对我是如何做到这一点有点模糊,但这里是我在 Rails 4.2 中使用的部分:

    首先,我创建了一个名为 :other_photos 的新文本列并对其进行了迁移。下一个:

    在模型中:

    serialize :other_photos, Array

    在控制器中:

    设置权限:

    params.require(:record).permit(:name, :caption, {:other_photos =&gt;[] })

    def create
      @record = Record.new(record_params)
      @record.other_photos = params[:other_photos]     # this was the piece that held me back
    
      ...
    
    end
    

    在视图中:

    <%= form_for @record do |r| %>
      <%= text_field_tag "other_photos[]" %>    
      <%= text_field_tag "other_photos[]" %> 
      <%= text_field_tag "other_photos[]" %>      # "r.text_field" didn't work for some reason
    
      ...
    
    <% end %>
    

    【讨论】:

    • 原因是 rails 会为给定的表单构建器属性寻找符号或字符串。所以你需要一个 text_field_tag 来给它任意名称,然后正如 ogz 的@Wizard 所说,你可以使用 rails 如何使用数组和表单参数来获取信息!
    【解决方案2】:

    请勿在字段名称的方括号内添加索引。请参阅guide on passing Arrays through params。在该指南中,数组示例使用 URL 查询字符串参数显示,但相同的原则适用于表单编码参数。

    <%= r.text_field "other_photos[]", size: 50 %>
    

    您可以根据需要添加任意数量的此类字段

    <%= r.text_field "other_photos[]", size: 50 %>
    <%= r.text_field "other_photos[]", size: 50 %>
    <%= r.text_field "other_photos[]", size: 50 %>
    

    然后params[:record][:other_photos] 将有一个数组值,其中包含表单上每个输入的元素。

    请小心,因为空文本输入仍将被提交并以空字符串结束。例如,如果只有上面显示的三个输入中的第一个被赋予了一个值,那么 other_photos 将被设置为类似["photo_url.png", "", ""]

    【讨论】:

    • 我让它工作了!我仍然很困惑,但我会在下面发布解决方案。
    猜你喜欢
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多