ActiveRecord::RecordInvalid: Validation failed: Technologies portfolio must exist

General Tech Technology & Software 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Technology & Software related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I was trying to save nested attributes for technologies with portfolio, I have the following code: portfolio.rb (model)

class Portfolio < ApplicationRecord
  has_many :technologies
  # do not accept the insertion if name is blank
  accepts_nested_attributes_for :technologies,
                                 reject_if: lambda{ |attrs| attrs['name'].blank? }
  validates_presence_of :title, :body, :main_image, :thumb_image
  include Placeholder
  validates_presence_of :title, :body, :main_image, :thumb_image

  # class method - custom scope
  def self.angulars
    where(subtitle: "Angular")
  end 

  # lambda - custom scope
  scope :ruby_on_rails_p_items, -> { where(subtitle: "Ruby on Rails") }

  # callbackss
  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

technology.rb model:

class Technology < ApplicationRecord
  belongs_to :portfolio
end

Now when I go to the rails console and try to insert multiple attributes:

Portfolio.create!(title: "Web App", subtitle: "asadasd", body: "sadsadas", technologies_attributes: [{name: "Ruby"}, {name: "Rails"}, {name: "Angula"}, {name: "Ionic"}])

It gave me this error:

ActiveRecord::RecordInvalid: Validation failed: Technologies portfolio must exist
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/validations.rb:78:in `raise_validation_error'

Any idea what am I missing here?

Schema for both technology and portfolio:

  create_table "portfolios",
                                                
                                                
0 views
0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.