代码之家  ›  专栏  ›  技术社区  ›  Chap

窗体生成器对象的字段为零

  •  35
  • Chap  · 技术社区  · 15 年前

    有没有办法访问嵌套的form_bulder.object?

    ## controller
    @project = Project.new
    @project.tasks.build
    
    form_for(@project) do |f|
      f.object.nil? ## returns false
    
      fields_for :tasks do |builder|
        builder.object.nil? ## returns true
      end
    end
    
    2 回复  |  直到 10 年前
        1
  •  65
  •   Chap    15 年前

    为了传递对象,必须在项目模型中接受的嵌套属性。

    class Project < ActiveRecord::Base
      has_many :tasks
      accepts_nested_attributes_for :tasks ## this is required
    end
    
        2
  •  12
  •   Matt Connolly    10 年前

    fields_for 要求方法 tasks_attributes= 存在。 accepts_nested_attributes_for :tasks 为您创建此方法,但您也可以自己定义它:

    def tasks_attributes=(params)
      # ... manually apply attributes in params to tasks
    end
    

    如果此方法不存在,则 builder.object 结果是没有。