开发者

How to give foreign key a name in RoR 3?

开发者 https://www.devze.com 2023-02-10 19:26 出处:网络
How can I give foreign key a name in RoR? I use following command to give foreign key:开发者_JAVA技巧

How can I give foreign key a name in RoR?

I use following command to give foreign key:开发者_JAVA技巧

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:

  • 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消