Hi I am not sure how foreign keys work here, i used belongs_to and has_many and created an extra attribute for the foreign key my question is how can i say this is the foreign key
Thanks in advance
Hi I am not sure how foreign keys work here, i used belongs_to and has_many and created an extra attribute for the foreign key my question is how can i say this is the foreign key
Thanks in advance
If the schema follows AR naming conventions the FK is inferred.
For example, if post has many comments
has_many :comments, :dependent => :destroy
and a comment belongs to a post
belongs_to :post
and the FK in the comments table is called post_id, you're done. AR will figure it out.
If the column is called something else there's an option to specify which is the FK, but if you're defining a new schema it is better (and expected) to just follow the conventions.
Assuming that you follow the Rails conventions then you do not need to, so if you have Foo belongs to bar and Bar has many foos, then Rails will expect the foos table to have a column bar_id as the foreign key.
However you may like to look at the foreigner gem which allows foreign key constraints to be applied to the database to prevent invalid foreign keys being saved. If you are just starting then it is not necessary to do this for the moment. I recommend it for production however.
I suggest running through some guides and tutorials which will help you to understand how all this works. railstutorial.org is a good free online tutorial and you should look at the Rails Guides also.
Colin