Foreign keys and migrations


#1

Hi:

I’m looking to get a point clarified which i’m sure is obvious to
everyone else but I haven’t been able to find the answer to. i’ve
tried searching through the forums and the api pages and haven’t found
anything.

Is there a way with migrations to set up foregin key relationships?
(beyond putting in the relevant foregin_id attributes)

Is that just supposed to be handeled at the model level with
“belongs_to” and “has_many” .etc… ?

I guess what I’m asking is whether relationships should just be handeled
at the business level or at the business level and data level? Is there
a best practices issue at work here?

lots of questions I know but I’m trying hard to learn:)

thanks!

Andrew


#2

On Sun, 2006-04-02 at 04:02 +0200, Andrew G. wrote:

Is that just supposed to be handeled at the model level with
“belongs_to” and “has_many” .etc… ?

I guess what I’m asking is whether relationships should just be handeled
at the business level or at the business level and data level? Is there
a best practices issue at work here?

lots of questions I know but I’m trying hard to learn:)


assuming that rails 1.1 didn’t change these things (and I didn’t notice
an indication that it did change), I have them added at the bottom of
the appropriate migration file in raw sql form…

just before the ‘end’ tag for def self.up…

# set up foreign key restratints for PostgreSQL
execute 'ALTER TABLE ONLY clients ADD CONSTRAINT fk_cp_case_manager

FOREIGN KEY (case_manager_id) REFERENCES case_managers(id);’

etc. (note that my mail client will cause this to wrap on 2 lines but I
don’t know that is significant).

Craig


#3

Craig W. wrote:

execute 'ALTER TABLE ONLY clients ADD CONSTRAINT fk_cp_case_manager

FOREIGN KEY (case_manager_id) REFERENCES case_managers(id);’

Do you need to set up foreign keys. I did not, and everything seems to
be working…


#4

On Sun, 2006-04-02 at 15:16 +0200, oom tuinstoel wrote:

Craig W. wrote:

execute 'ALTER TABLE ONLY clients ADD CONSTRAINT fk_cp_case_manager

FOREIGN KEY (case_manager_id) REFERENCES case_managers(id);’

Do you need to set up foreign keys. I did not, and everything seems to
be working…


No - rails obtains the information from the models. This is for
PostgreSQL - i.e. if you are using the tables with other client
applications.

Craig


#5

subversion is your friend (version control)

svn revert

Craig


#6

On a slight aside, one thing that would be nice is if you could
migrate the models along with the database. If I have to skip back to
a different version of my database for any reason, I find myself
having to comment out and change parts of my model to prevent it from
going all wrong.
-Nathan