【问题标题】:has_many nested form with has_one insidehas_many 嵌套表格,里面有 has_one
【发布时间】:2013-09-26 10:54:39
【问题描述】:

我遇到了类似的问题 has_many nested form with a has_one nested form within it

基本上尝试在创建客户端的同时创建任务,其中一些任务可能会重复出现,这些任务通过与重复模型的 has_one 关系进行处理。

所以。

客户端模型

    attr_accessible :tasks_attributes
    has_many :tasks, dependent: :destroy
    accepts_nested_attributes_for :tasks, :allow_destroy => true, :reject_if => lambda { |t| t['task_type'].blank? }

任务模型

     belongs_to :client
     has_one :recurring, :dependent => :destroy
     accepts_nested_attributes_for :recurring, :reject_if => lambda { |t| t['recurring_type'].blank? }
     attr_accessible :recurring_attributes

Clients_controller

def new
@client = Client.new 
@task = @client.tasks.build

客户/_form

    <table id="tasks" class="table table-striped">
      <%=f.simple_fields_for :tasks, :wrapper => false  do |task|%>
        <tr class="fields>
                <td><%=task.input :task_type, :label => "Task Type", :collection => Task::TASK_TYPES %></td>
                <td>
                  <%= task.simple_fields_for :recurring, @task.build_recurring do |recur|%>
                    <%= recur.input :recurring_type, :as => :select, :collection => Recurring::RECUR_TYPES %>
                  <%end%>
                </td>
                <td><%= task.input :due_date, :as => :datepicker, :label => "Next Due Date"%></td>
                <td><%= task.link_to_remove "Remove this task" %></td>
            <%end%>
        </tr>
        </table>
        <%= f.link_to_add "Add a task", :tasks, :data => { :target => "#tasks" } %>

我可以让表单正确显示,它现在可以正确添加和删除任务。 但是当我提交时,我得到一个

    undefined method `build_recurring' for nil:NilClass

我现在正在第五次尝试以不同的方式这样做,这让我发疯了。

任何想法我做错了什么?

【问题讨论】:

  • 循环模型是什么样的?您有与名为 Recurring 的模型关联的任务 - 它存在吗?
  • 循环模型belongs_to 任务。它基本上只是在必要时保存任务的重复标准。
  • 如果 Recurring 模型仅包含 recurring_type 属性并放入 Task.但是除此之外,您是否尝试过 simple_form 关联 github.com/plataformatec/simple_form#associations ?也许像
  • 还有其他原因让我想保持定期分开。如果我只是删除重复位,它似乎有效,但我添加的只是下拉列表中的一个值,它不接受它。真的很烦人。
  • 只是为了解释一下,将重复标准与任务的单个实例分开是很重要的,因为一旦单个任务被修改,我们需要识别重复(作为提供无限重复的一种方式没有在数据库中持久化无限的东西)。

标签: ruby-on-rails nested-forms simple-form


【解决方案1】:

问题是由于reject_if 而出现的。它拒绝出现错误时出现的空白字段,因此该字段未显示。

删除reject_if为空白可以改为nil,之后验证可以作为常规验证处理。

【讨论】:

  • 仍然没有解决问题。即仍然无法使用重复数据添加多个任务。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
相关资源
最近更新 更多