0

我正在尝试按照http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes中所述使用 Accepts_nested_attributes_for

我假设教程中的第二个代码块应该在模型中,因为他后来说对控制器什么都不做。不过,示波器似乎向控制器代码发出信号。我已将以下代码添加到“扫描”模型中,该代码应该在创建扫描之前生成子“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

但是,当我尝试创建扫描时,出现以下错误:

NoMethodError in ScansController#create

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

它似乎不知道 HostScans_attributes。

4

2 回答 2

1

首先,尝试使用under_score符号而不是camelCase- rails 期望按照惯例。使用嵌套属性时,您需要声明一个属性助手以使用 - 在这种情况下 :host_scans_attributes (或 :hostScans_attributes 如果声明为 camelcase),如下所示:

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
于 2012-05-22T17:27:46.267 回答
0

attr_accessible在你的模型中使用,它基本上是所有可以被大量分配的属性的白名单。所以你还需要在attributes那里添加......

于 2012-05-22T17:28:37.917 回答