How to specify a foreign key in RoR 3?

How to specify a foreign key in RoR?

I use the following command to specify a foreign key:

rails generate scaffold Table2 id:integer Table1:references

This command adds foreign key of Table1 in Table2, but with a default name Table1_id. So, how can I specify a custom name for it, for example my_table_f_keyinstead Table1_id.

I am using Ruby 1.9.2 and Rails 3.0.3.


Edit: -

In my model project.rb:

belongs_to :own, :class_name => User

In my model user.rb:

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, for example, project.owner.useridit throws an exception.

+3
source share
2 answers

Based on your answers in the comments, this is one way to implement what you want to do:

( ) :

  • , Question belongs_to Asker
  • , Question _

:

rails generate scaffold Question asker_id:integer editor_id:integer

id:integer , Rails . (.. asker_id).

:

class Question < ActiveRecord::Base
  belongs_to :asker, :class_name => User
  belongs_to :editor, :class_name => User
end

class User < ActiveRecord::Base
  has_many :asked_questions, :class_name => Question, :foreign_key => :asker_id
  has_many :edited_questions, :class_name => Question, :foreign_key => :editor_id
end

, :

@question.asker # => User
@question.editor # => User

@user.asked_questions # => [Question, Question, Question]
@user.edited_questions # => [Question, Question]

, .

+7

@Dan , String.

DEPRECATION WARNING: class_name ArgumentError in Rails 5.2. , , .

class Question < ActiveRecord::Base
  belongs_to :asker, :class_name => User
  belongs_to :editor, :class_name => User
end

class User < ActiveRecord::Base
  has_many :asked_questions, :class_name => 'Question', :foreign_key => :asker_id
  has_many :edited_questions, :class_name => 'Question', :foreign_key => :editor_id
end
0

Source: https://habr.com/ru/post/1792709/


All Articles