简体   繁体   中英

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

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:

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

The Portfolio.rb file:

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM