我正在尝试使用[{3}}
中所述的accepts_nested_attributes_for我认为教程中的第二个代码块应该在模型中,因为他后来说对控制器什么都不做。但是,范围似乎是控制器代码的信号。我已将以下代码添加到“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
但是,当我尝试创建扫描时,出现以下错误:
NoMethodError in ScansController#create
undefined method `HostScans_attributes' for #<Scan:0x2441e68>
它似乎不知道HostScans_attributes。
答案 0 :(得分: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
答案 1 :(得分:0)
您在模型中使用attr_accessible
,这基本上是所有属性的白名单,可以是大规模分配。所以你需要在那里添加attributes
......