views:

28

answers:

1

I'm just learning Ruby on Rails (no prior Ruby experience) I have these models (not showing the migrations here for brevity - they're standard fields like firstname, city etc):

class User < ActiveRecord::Base
  has_one :address
end

class Address < ActiveRecord::Base
  has_one :user
end

How do I use the Address class to manage the underlying table data? Simply call methods on it? How would I pass params/attribute values to the class in that case? (since Address won't have a controller for it (since it's meant to be used internally)). How does one go about doing something like this?

A: 
u = User.create :first_name => 'foo', :last_name => 'bar' #saves to the database, and returns the object
u.address.create :street => '122 street name' #saves to the database, with the user association set for you

#you can also just new stuff up, and save when you like
u = User.new
u.first_name = 'foo'
u.last_name ='bar'
u.save

#dynamic finders are hela-cool, you can chain stuff together however you like in the method name
u = User.find_by_first_name_and_last_name 'foo', 'bar'

#you also have some enumerable accessors
u = User.all.each {|u| puts u.first_name }

#and update works as you would expect

u = User.first
u.first_name = 'something new'
u.save

#deleting does as well

u = User.first
u.destroy

There is more to it then just this, let me know if you have any questions on stuff I didn't cover

Matt Briggs