How to give foreign key a name in RoR 3?

感情迁移 提交于 2019-12-05 03:01:40

问题


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.


回答1:


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:

  • User asks many Questions, Question belongs_to Asker
  • User edits many Questions, Question belongs_to Editor

You could implement this structure in the following way:

rails generate scaffold Question asker_id:integer editor_id:integer

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:

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

That way, you can use them together like this:

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

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

Hope this helps.




回答2:


Adding to @Dan's answer, pass the class name as String.

DEPRECATION WARNING: Passing a class to the class_name is deprecated and will raise an ArgumentError in Rails 5.2. It eagerloads more classes than necessary and potentially creates circular dependencies. Please pass the class name as a string

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


来源:https://stackoverflow.com/questions/5025135/how-to-give-foreign-key-a-name-in-ror-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!