0

我对rails很陌生,所以请原谅我的无知。但我目前有一个控制器,它为理论上的病毒扫描程序存储“扫描结果”。

扫描模型,has_many Detections,它是一个包含 Sha256 哈希和类型的记录。

代码如下

model/scan.rb

class Scan < ApplicationRecord
    has_many :detections, class_name: "detection", foreign_key: "d_id", :dependent => :destroy
    accepts_nested_attributes_for :detections
    validates :hostname, presence: true, uniqueness: { case_sensitive: true }, length: {maximum: 50, minimum: 1}, if: :hostname_not_empty
    
    

    def hostname_not_empty 
        if ( self.hostname != '' || self.hostname.nil? )
            return true
        end
        return errors.add(:scansErr, "Hostname is empty")
    end
end

model/detections

class Detection < ApplicationRecord
  belongs_to :scan
  validates :hash, presence: true, length: {maximum: 64, minimum:64}, format: { with: /\b[A-Fa-f0-9]{64}\b/ }
  
  def new () 

  end 
  def new_record
  end
end

当我尝试创建用于向数据库添加新扫描的模板时,出现此错误 hash is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name

我正在使用以下模板来尝试渲染它。

views/dashboard/form.html.haml

...
= form_for :scans, url: dashboard_scan_create_path(params.to_unsafe_h.slice(:hostname)), :html => {:class => 'flex w-full flex-col scan-form' } do |s|
        %div.flex.w-full.relative
          #{s.text_field :hostname, :class => 'input border border-gray-400 appearance-none rounded w-full px-3 py-3 pt-8 pb-2 my-2 focus focus:border-indigo-600 focus:outline-none active:outline-none active:border-indigo-600' }
          #{s.label :hostname, :class => 'label absolute mb-0 -mt-2 pt-4 pl-3 leading-tighter text-gray-400 text-base mt-2 cursor-text'}
        %div.detections.flex.w-full.my-2{ 'data-controller' => 'detection-form' }
          %div.text-xl.font-bold Detections
          %template{"data-target" => "detection-form.template"}
            = s.fields_for :detections, Detection.new, child_index: "NEW_RECORD" do |d_form|
              = render "detection_fields", form: d_form
...

views/dashboard/detections-fields.html.haml

= content_tag :div, class: "detection-fields" do
  .input.detection-field-input.d-flex.justtify-content-between.mb-2
    .col-11.pl-0
      = form.fields_for(:detection) do |detection_form|
        = detection_form.text_field :type
        = detection_form.text_field :hash
    .col-1
      = link_to "delete", "#", data: { action: "nested-form#remove_association" }
  = form.hidden_field :_destroy, as: :hidden


谁能帮我弄清楚我做错了什么。

4

1 回答 1

1

错误很明显,因为ActiveRecord::Core它定义了一个方法hash,而您的模型Detection有一个名为 的冲突属性hash

此处的操作是将hash模型的属性重命名为尚未实现/保留的属性。

例如,如果您将模型属性(以及使用它的相关代码)更改为 be sha256,否则sha它将避免冲突。

于 2020-11-13T00:38:24.167 回答