【问题标题】:Handling differents parameters in the same form with the same model相同模型处理相同形式的不同参数
【发布时间】:2013-08-15 15:44:57
【问题描述】:

假设我有一个 ProblemRestriction 模型类。问题有很多限制,并接受嵌套属性作为限制。 Restriction 模型表示如下数学表达式:

  • X
  • 1
  • 2

当我通过表单创建Problem 时,我还必须创建限制(始终为 3)。

对于限制表格,我填写了数字。即:X < [Input a number] 请注意,第二个限制需要填写两个字段,但第一个和第三个只需要一个。 如何使用不同的参数在问题控制器中创建每个限制? 对于第一个和第三个限制,我只需要传递一个数字,但第二个我需要传递两个数字(也许还有两个数字的数组)

如果我不清楚,请告诉我。

【问题讨论】:

  • 如果没有Restriction 的架构就无法判断。
  • 我的回答有帮助吗?
  • 我现在试试

标签: ruby-on-rails forms ruby-on-rails-4 rails-activerecord


【解决方案1】:

您可以使用空数组设置输入的名称:

number_field_tag 'problem[restrictions][1][]', 0
number_field_tag 'problem[restrictions][1][]', 5

然后在您的 ProblemController 中,您应该会收到如下参数:

params[:problem][:restrictions][1]
# => contains the 2 values serialized as array

所以完整的形式是:

X < 
<%= number_field_tag 'problem[restrictions][0]', 0 %>

<%= number_field_tag 'problem[restrictions][1][]', 0 %>
<= X <=
<%= number_field_tag 'problem[restrictions][1][]', 5 %>

<%= number_field_tag 'problem[restrictions][2]', 0 %>
< X

你最终会得到以下参数:

params = {
  problem: { #all the Problem attributes filled in the form },
  restrictions: 
  [
    <value of first input>,
    [<value of second input>, <value of third input>],
    <value of fourth input>
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多