Foreign key question


Say I have a db with following schema:

Id, name, user_id, date

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?



I think you’re confusing things a bit.

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

belongs_to :user

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.


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…

belongs_to :user

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?


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

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 <%= %>)


Great, thank you!

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs