简体   繁体   English

使用accepts_nested_attributes_for

[英]using accepts_nested_attributes_for

I'm trying to use accepts_nested_attributes_for as described at http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes 我正在尝试使用http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes中所述的accepts_nested_attributes_for

I assumed that second block of code in the tutorial is meant to be in the model, since he says later to do nothing to the controller. 我以为教程中的第二个代码块应该在模型中,因为他稍后说对控制器什么也不做。 The scope seems to signal controller code, though. 但是,该范围似乎表明了控制器代码。 I have added the following code to the model for "scan", which is supposed to generate child "hostScan" objects before creation of a scan 我已将以下代码添加到“扫描”的模型中,该代码应在创建扫描之前生成子“ hostScan”对象

class Scan < ActiveRecord::Base
  attr_accessible :description, :endTime, :startTime, :raw
  has_many :hostScans, dependent: :destroy
  accepts_nested_attributes_for :hostScans, :allow_destroy => true

  before_create :interpret

  def interpret

    #parse the start and end times of the scan
self.startTime = raw.split(/(?<=timestamps\|\|\|scan_start\|)(.*?)(?=\|)/)[1]
self.endTime = raw.split(/(?<=timestamps\|\|\|scan_end\|)(.*?)(?=\|)/)[1]

#host scan bodies
    #host name
        #hostScans = raw.scan(/(?<=timestamps\|\|)(.*?)(?=\|host_start)/)
        #self.HostScans_attributes = [{}]
    #raw host text
        hostScanBodies = raw.split(/(?<=host_start\|)(.*?)(?=host_end)/)

        hostScanBodies.each do |body|
            self.HostScans_attributes += [{:raw => body}]
        end
  end
end

However, when I try to create a scan, I get the following error: 但是,当我尝试创建扫描时,出现以下错误:

NoMethodError in ScansController#create

undefined method `HostScans_attributes' for #<Scan:0x2441e68>

It doesn't seem to know about HostScans_attributes. 似乎不了解HostScans_attributes。

Firstly, try using under_score notation rather than camelCase - rails expects that by convention. 首先,尝试使用under_score表示法而不是camelCase -Rails期望按照惯例。 When using nested attributes, you need to declare an attribute helper to work with - in this case :host_scans_attributes (or :hostScans_attributes if declared as camelcase) like this: 使用嵌套属性时,您需要声明一个可使用的属性助手-在这种情况下,:host_scans_attributes(如果声明为camelcase,则为:hostScans_attributes),如下所示:

class Scan < ActiveRecord::Base
  attr_accessible :description, :end_time, :start_time, :raw, :host_scans_attributes
  has_many :host_scans, dependent: :destroy
  accepts_nested_attributes_for :host_scans, :allow_destroy => true

You're using attr_accessible in your model, which is basically a whitelist of all the attributes which can be mass assigend. 您在模型中使用的是attr_accessible ,这基本上是所有可以大量使用的属性的白名单。 So you need to add the attributes there as well... 因此,您还需要在其中添加attributes ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM