Foreign key question

Hi-

Say I have a db with following schema:

MyTable:
Id, name, user_id, date

User:
id, name, description

I know that I want to add “belongs_to” in my “user” model but how can
I enforce a proper constraint on the user_id in “MyTable”? Is this
done using a has_one in the “MyTable” model?

Thanks!

Hello,

I think you’re confusing things a bit.

With the tables you describe you should put the following into your
models:

my_table.rb
belongs_to :user

user.rb
has_many :my_tables
(or has_one :my_table)

If you want it the other way around, you should put the foreign key
my_table_id in your User model.

Regards

how can I enforce a proper constraint on the user_id in “MyTable”?

If you mean constraints on a database level: you will have to put those
in manually. AFAIK Rails itself (e.g. migrations) do not provide support
for database level constraints of anything other than datatype (and
length). There surely is a plugin around though…

  • Niels.

Cool, this helps. One more clarification…since “MyTable” was a
really bad example…

job_posting.rb
belongs_to :user

user.rb
has_many :job_postings

So, say I want to link a user to a job posting, a user can have many
job postings but I want to make sure that the user being referenced is
a real user. Is this the correct approach?

Thanks!

Yes, that should be fine, but maybe you should add:

user.rb
has_many :job_postings, :dependent => :destroy

Now if your user record is deleted, all it’s job postings are also
removed from the DB. Otherwise there 's a big chance you 'll get
nil-errors in your views (eg. when you try to display <%=
job_posing.user.name %>)

Stijn

Great, thank you!

On Mar 21, 3:51 pm, Stijn P. [email protected]