Has_one/belongs_to relationship issue

I’m trying to set up a has_one/belongs_to relationship. I have no
problem setting up a has_many/belongs_to relationship, but when I try to
make it a has_one relationship I get an undefined method error if I try
to call the belongs_to relationship through the has_one relationship.

user = User.find_by_display_name(“shoxz”)
user.story.create(:title => “hello”) or
user.stories.create(:title => “hello”) or
user.story.new(:title => “hello”) or
user.stories.new(:title => “hello”) or
user.story << Story.new(:title => “hello”)

NoMethodError: undefined method story' for #<User:0x221a478> from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:1792:inmethod_missing’

If I change the code to has many and do the following it works fine:

user = User.find_by_display_name(“shoxz”)
user.stories.create(:title => “hello”)

I only want a user to have one story and need it to work the other way.
I’ve checked reserved and magic words and that’s not the issue. I’ve
tried everything and have read everything.

I’d appreciate any help or any ideas at all.

Thanks,

S.

Code follows:

class User < ActiveRecord::Base
has_one :story
end
class Story < ActiveRecord::Base
belongs_to :user
end
ActiveRecord::Schema.define(:version => 4) do
create_table “stories”, :force => true do |t|
t.column “title”, :string
t.column “user_id”, :integer
end
create_table “users”, :force => true do |t|
t.column “display_name”, :string
end
end

Cacye came up with the solution:

When it is a has_one relationship you inject it with an ‘=’ rather than
directly or with ‘<<’. That’s a good point, and I wish it was published
somewhere because I’ve been looking for a couple days goign crazy
throught all of the wikis and google.

My mistake - I was thinking “has_many”, didn’t connect that it was
“has_one”.

How about:

user.profile = Profile.new(:hello => "yeah")

c.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs