Beginner: what to do after adding an association in a model?


#1

I’ve looked at a bunch of tutorials and don’t really understand what
is supposed to happen after I add an association (belongs_to, has_many
etc) to both sides of a relationship.

A lot of the tutorials just add the associations and move on as if
that’s it, but when I add the association nothing has changed in the
db (which makes sense because at this point I’ve only changed code).
Is there a command I’m supposed to run to look at all the
relationships and add tables/columns for relationships that are
missing them? or am I supposed to manually create the table?


#2

On Mar 12, 6:05 am, neerolyte removed_email_address@domain.invalid wrote:

I’ve looked at a bunch of tutorials and don’t really understand what
is supposed to happen after I add an association (belongs_to, has_many
etc) to both sides of a relationship.

A lot of the tutorials just add the associations and move on as if
that’s it, but when I add the association nothing has changed in the
db (which makes sense because at this point I’ve only changed code).
Is there a command I’m supposed to run to look at all the
relationships and add tables/columns for relationships that are
missing them? or am I supposed to manually create the table?

You’re suppose to use migrations to add columns or create tables (see
http://guides.rubyonrails.org/migrations.html )

Fred


#3

I dont think so you need to do any thing manually with the db…
Just use the association by using dot operator.
Regards
Rabia


#4

Does that mean I have to write a custom migration for it, the only
automated migrations I can find are for adding/removing columns
(AddXXXtoYYY).

Is there something like AddHasAndBelongsToManyModelXToModelY?

Dave.

2009/3/12 Frederick C. removed_email_address@domain.invalid:


#5

So building on that example, you should add a column person_id to the
address table. Rails will infer the foreign key based on rails model
names. U can also specify the actual column by passing :foreign_key
into belongs_to macro.

Roman


#6

The associations you create in a model have to be backed up by the
appropriate fields in the DB.

For example:

class Person
has_many :addresses

class Address
belongs_to :person

should be a model representation of the relationship inherent in the
database (the two really go hand-in-hand).

if:

Table people
id:integer
first_name:string
last_name:string

Table address
id:integer
person_id:integer
line1:string
line2:string
city:string
state:string
postal_code:string

has_many :addresses tells Rails that for a given person, it can use that
person id field to retrieve address records (those whose person_id
matches the current person id value). Similarly, from an address, Rails
can get back to the person record by following the person_id on the
address.