2012-05-22 103 views
0

我想作爲http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes使用accepts_nested_attributes_for

描述我認爲在教程代碼第二塊,就是要在模型中,因爲他後來回憶說,什麼也不做控制器使用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。

回答

1

首先,嘗試使用under_score表示法而不是camelCase - rails期望按慣例。當使用嵌套的屬性,你需要聲明一個屬性助手一起工作 - 在這種情況下:host_scans_attributes(或: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 
+0

謝謝。我相信我更接近,但它仍然無法工作。同樣的基本問題:未定義的方法'host_scans_attributes'爲#<掃描:0x23b97b8> – blaha

+0

並且您已將':host_scans_attributes'添加到'attr_accessible'列表,對吧? – PinnyM

+0

是的。 attr_accessible:description,:endTime,:startTime,:raw,:host_scans_attributes – blaha

0

你在你的模型,用attr_accessible這基本上是一個可以大衆化的所有屬性的白名單。所以你需要在那裏添加attributes ...

+0

這將是attr_accessible:description,:endTime,:startTime,:raw,:host_scans_attributes,對吧? – blaha

相關問題