簡體   English   中英

RoR-嵌套屬性的參數個數錯誤?

[英]RoR - Nested attributes wrong number of arguments?

當前正在學習一個教程,該教程應實現嵌套表單。 但是,當我運行rails c並嘗試使用嵌套屬性創建新的Portfolio時,我得到了

ArgumentError: wrong number of arguments (given 1, expected 0)
    from app/models/portfolio.rb:4:in `block in <class:Portfolio>'
    from (irb):15

命令我在rails內運行:

Portfolio.create!(title: 'Title', subtitle:'Title1', body:'Title3',
technologies_attributes:[{name: 'Ruby'}])

Portfolio.rb文件:

class Portfolio < ApplicationRecord
  has_many :technologies
  accepts_nested_attributes_for :technologies,
                                reject_if: lambda { |attrs| attrs['name'].blank? }


  include Placeholder
  validates_presence_of :title, :body, :main_image, :thumb_image

  def self.angular
    where(subtitle: 'Angular!')
  end

  def self.ruby
    where(subtitle: 'Ruby on Rails!')
  end

  after_initialize :set_defaults

  def set_defaults
    self.main_image ||= Placeholder.image_generator(height: '600', width: '400')
    self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')
  end

end

任何想法會導致什么?

提前致謝!

好像您要傳遞一個哈希數組作為此處的嵌套屬性

Portfolio.create!(title: 'Title', subtitle:'Title1', body:'Title3', technologies_attributes:[{name: 'Ruby'}])

嘗試像這樣傳遞屬性

params = {
    portfolio: { title: 'Title', subtitle:'Title1', body:'Title3',
        technologies_attributes:[
            {name: 'Ruby'}
        ]
    }
}
Portfolio.create!(params)

嘗試在兩個模型中都使用inverse_of :,因為它曾經用於創建關聯的對象。

class Portfolio < ApplicationRecord
  has_many :technologies, inverse_of: :port_folio
end

class Technology < ApplicationRecord
  belongs_to :port_folio, inverse_of: :technologies
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM