0

http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributesで説明されているように、accepts_nested_attributes_for を使用しようとしています。

チュートリアルのコードの 2 番目のブロックは、後でコントローラーに何もしないように言っているので、モデルにあると想定しました。ただし、スコープはコントローラー コードを通知しているようです。次のコードを「スキャン」のモデルに追加しました。これは、スキャンの作成前に子「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) です。

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 に答える