ruby on rails - Trying to build a one to one relationship between two preexisting models -


i new rails , trying build 1 one relationship between 2 preexisting models (test , test_type) in rails.

here workflow.

has_one :test_type - tests model belongs_to :test - test_types model rails g migration add_test_type_to_test test_type:references  rake db:migrate  

now looks has worked ok when try verify looks hasn't.

rails console @type = testtypes.new :name => "my type" @type.save @test = tests.new :name => "my test"  testtypes.find(1) //returns record ok @test.test_type //returns nil @test.test_type = testtypes.find(1) //nameerror: uninitialized constant tests::testtype @test.test_type //still nil 

according output finds type in database doesn't seem able add test class indicates me relationship not working.

is able tell doing wrong?

does work if change 1 line of code belongs_to :test -> has_one :test make one-on-one relationship. think error comes fact have not added test_type instance test_type attribute of test object. before making @test.test_type request need add @test.test_type = @test_type. if wanna save change database update_attribute method useful purpose update_attribute(name, value), @test.update_attribute('test_type', @test_type)

updated answer: rails guide says:

4.2.1 methods added has_one

when declare has_one association, declaring class automatically gains 5 methods related association:

association(force_reload = false) association=(associate) build_association(attributes = {}) create_association(attributes = {}) create_association!(attributes = {} 

so try @test.create_test_type(test_id: test.id), bit of code can replace following code mentioned earlier @test.test_type (sorry i'm not rails expert - still learning)


Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -