has_many
     vs
   has_one
2010/10/02 Shouichi KAMIYA
Given
class App ActiveRecord::Base
    has_many :servers
end


class Server ActiveRecord::Base
    belongs_to :app
end
Then

irb> app = App.new

irb > app.servers = [Server.new]

irb > app.servers

#=> [#<Server:0x101141d68>]
Looking good.
Given
class App ActiveRecord::Base
    has_one :server
end


class Server ActiveRecord::Base
    belongs_to :app
end
Then

irb> app = App.new

irb > app.server = Server.new

irb > app.server

#=> nil
What!?
The correct way

irb> app = App.new

irb > app.set_server_target = Server.new

irb > app.server

#=> #<Server:0x101141d68>
WTF...
         Thanks!
Upcoming SlideShare
Loading in …5
×

Rails: has_many vs has_one

2,403 views
2,263 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,403
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide









  • Rails: has_many vs has_one

    1. 1. has_many vs has_one 2010/10/02 Shouichi KAMIYA
    2. 2. Given class App ActiveRecord::Base has_many :servers end class Server ActiveRecord::Base belongs_to :app end
    3. 3. Then irb> app = App.new irb > app.servers = [Server.new] irb > app.servers #=> [#<Server:0x101141d68>]
    4. 4. Looking good.
    5. 5. Given class App ActiveRecord::Base has_one :server end class Server ActiveRecord::Base belongs_to :app end
    6. 6. Then irb> app = App.new irb > app.server = Server.new irb > app.server #=> nil
    7. 7. What!?
    8. 8. The correct way irb> app = App.new irb > app.set_server_target = Server.new irb > app.server #=> #<Server:0x101141d68>
    9. 9. WTF... Thanks!

    ×