Ask A Question

Notifications

You’re not receiving notifications from this thread.

Error message is displayed One to one relationship with Ruby on Rails

prabu asked in Rails

Hi Everone,
i am trying to create one to one relationship with ruby on rails5.

  1. I ahve created the Dubject model in the below format class Subject < ApplicationRecord has_one :page
    scope :visible, lambda { where(:visible => true) } scope :invisible, lambda { where(:visible => false) } scope :sortedASC, lambda {order ("position ASC")} scope :sortedDESC, lambda {order ("position DESC")} scope :newest_first, lambda {order ("created_at DESC")} scope :search, lambda {|query| where(["name LIKE ?", "%#{query}%"])} end
    1. I have created the page model in the below format.

class Page < ApplicationRecord
belongs_to :subject
end

I am able to save the subject record. When i create the page object for page model and assigning to the subject. i am getting the below error.

  1. subject=Subject.find(5)!

Adding new recrord to the page table and assingning the object referrence to Subject model

  1. first_page=Page.new(:name=>"First page", :permalink=> 'first', :position=>1)

  2. subject.page= first_page
    Error message:

(0.5ms) BEGIN
(0.0ms) ROLLBACK
ActiveRecord::RecordNotSaved: Failed to save the new associated page.
from (irb):49

Could any one help me fix this error.

Thanks
Prabu

Reply

Try this:

subject = Subject.find(5)
subject.create_page(name: 'First Page', permalink: 'first', position: 1)

See: http://guides.rubyonrails.org/association_basics.html#has-one-association-reference

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 77,200+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.