繁体   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