How can I give foreign key a name in RoR?
I use following command to give foreign key:
rails generate scaffold Table2 id:integer Table1:references
This command adds foreign key of Table1 in Table2
but with default name that is Table1_id
. So how can I give custom name to it for example my_table_f_key
instead of Table1_id
.
I'm using Ruby 1.9.2 and Rails 3.0.3.
Edit:-
In my project.rb
model:
belongs_to :own, :class_name => User
In my user.rb
model:
has_many :owned_projects, :class_name => Project, :foreign_key => :owner
how I created my project model
rails generate scaffold Project name:string owner:integer
Now when I access user_id from Project like
project.owner.userid
it throws exception.
Based on your responses in the comments, this is one way of implementing what you want to do:
Assuming two models in your app (Users and Questions), and two different relationships:
You could implement this structure in the following way:
Specifying
id:integer
in your generate command is redundant, as Rails will generate that column for you automatically. It's also conventional to name your foreign keys in terms of the relationship (ie,asker_id
).Then, inside each of your models:
That way, you can use them together like this:
Hope this helps.
Adding to @Dan's answer, pass the class name as String.