我有两张 table 。 “文章”和“书签”。我想定义它们之间的关联。
文章表有'doi'列用于书签表。
文章:
| doi| varchar(255) | YES | MUL | NULL |
书签:
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_profile_id | int(11) | NO | MUL | NULL | |
| device_id | int(11) | NO | MUL | NULL | |
| article_doi | text | NO | | NULL | |
| disabled_at | varchar(255) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
由于某些原因,我无法使用文章的 ID 来引用书签表中的文章。现在我想将 dependent destroy 添加到在 article_doi 列中具有该特定文章 doi 的所有书签(删除文章时删除所有书签)。我怎样才能做到这一点?
文章表'doi'和书签表'article_doi'是否必须具有相同的名称才能用作外键?
最佳答案
我认为你只需要使用“foreign_key”选项
class Article < ActiveRecord::Base
has_many :bookmarks, dependent: :destroy, foreign_key: :article_doi
end
class Bookmark < ActiveRecord::Base
belongs_to :article, foreign_key: :article_doi
end
来源:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
关于mysql - Rails 依赖销毁非关联对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40356271/