简体   繁体   English

RoR-嵌套属性的参数个数错误?

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

Currently following a tutorial, where a nested form should be implemented. 当前正在学习一个教程,该教程应实现嵌套表单。 However, when i run rails c and try to create a new Portfolio with the nested attributes, i get an 但是,当我运行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

Command i ran inside rails c: 命令我在rails内运行:

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

The Portfolio.rb file: 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

Any ideas what would cause that? 任何想法会导致什么?

Thanks in advance! 提前致谢!

It looks like like you're passing an array of hashes as the nested attributes here 好像您要传递一个哈希数组作为此处的嵌套属性

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

Try passing the attributes like this 尝试像这样传递属性

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

Try using, inverse_of: in both the models, since it used to created associated objects. 尝试在两个模型中都使用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