Referential integrity


#1

I am starting out in rails and am loving it! Thanks to all the
contributors!

I made a web app that had about 7 models, with some referring to each
other, eg a team had a member and so on.

This relationship was not enforced in the model or in the database, it
was kind of hacked together in the view by creating html select
inputs.

I found very quickly that deleting models and adding new ones meant
that objects that should not be related were.

I thought at first I should implement the correct cascading deletes.
I have looked into this a little more and have now redefined all my
models correctly, eg a team has_many :members.

I looked at the mysql database this created and there are no foreign
key relationships.

question 1) should there be foreign key relations in mysql db? I used
the script/generate model and then rake db:migrate

my model:
class Developer < ActiveRecord::Base
belongs_to :team
end

question 2) in my conceptual model my developer belongs to a team. So
i have the model above. Should there be a relationship in team
describing how the link exists to developer? Currently mine is empty:
class Team < ActiveRecord::Base
end

thanks in advanced for any help!


#2

On Apr 13, 11:06 pm, doughie removed_email_address@domain.invalid wrote:

question 1) should there be foreign key relations in mysql db? I used
the script/generate model and then rake db:migrate

Rails has no native support for foreign key constraints in the DB. I
use the RedHillOnRails Core plugin, unfortunately there main site went
offline not long ago but you can get the plugin from:
http://github.com/harukizaemon/redhillonrails_core/tree/master. This
allows you to specify foreign keys in migrations if you want the
database to maintain referential integrity for you (dunno who
wouldn’t!).

question 2) in my conceptual model my developer belongs to a team. So
i have the model above. Should there be a relationship in team
describing how the link exists to developer? Currently mine is empty:
class Team < ActiveRecord::Base
end

You would say has_many :developers. The Rails API
ActiveRecord::Associations documentation provides an in-depth
discussion of relations.

Best regards,
Andrew


#3

Your Team has many members and should be noted:

class Team < ActiveRecord::Base
has_many :members
end

This is assuming that you have a column in your member table named
team_id. I think this is what you were asking about with the foreign
keys.

As a somewhat noob to Rails myself I found a few good books for
beginners to be the most help. The two I like the best are: “Simply
Rails 2” and “Agile Web D. with Rails”.