Ruby on rails 如何在RubyonRails中添加与自定义FK的关联?
我有两种模式:用户模式和微型模式。Ruby on rails 如何在RubyonRails中添加与自定义FK的关联?,ruby-on-rails,ruby,associations,Ruby On Rails,Ruby,Associations,我有两种模式:用户模式和微型模式。一对多之间存在关联。我想添加到microsposts字段replic\u to和replics\u fromtoUsers,以及与多对多关系的关联,这些关系不仅存储在作者的模型microsposts中,而且还存储在消息的用户ID中。由于模型之间已经存在关联,我认为需要将力场指定为新关联的FK。我请你展示一下如何做到这一点。先谢谢你 这方面的资料来源: class CreateUsers < ActiveRecord::Migration def cha
一对多
之间存在关联。我想添加到microsposts
字段replic\u to
和replics\u from
toUsers
,以及与多对多关系的关联,这些关系不仅存储在作者的模型microsposts
中,而且还存储在消息的用户ID中。由于模型之间已经存在关联,我认为需要将力场指定为新关联的FK
。我请你展示一下如何做到这一点。先谢谢你
这方面的资料来源:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps
end
end
end
class CreateMicroposts < ActiveRecord::Migration
def change
create_table :microposts do |t|
t.string :content
t.integer :user_id
t.timestamps
end
add_index(:microposts, [:user_id, :created_at]);
end
end
class User < ActiveRecord::Base
....
has_many(:microposts, dependent: :destroy);
....
end
class Micropost < ActiveRecord::Base
....
belongs_to :user;
....
end
class CreateUsers
添加到micropost.rb
belongs_to :replics_to, class_name: 'User'
相应的字段应为
add_column :microposts, :replics_to_id, :integer
对于user.rb
has_many :replics_from, class_name: 'User', foreign_key: 'replics_to_id'
查看有许多属于的不同选项(例如第2.10章“自联接”)