Rails: dependent delete of models where association has non-standard name -


i modeling directed graph in rails application (rails 4.2). among model objects vertex , edge.

a vertex can part of many edges - hence have following relationship:

vertex -- has_many --> edges 

an edge defined between 2 vertices - origin , terminus. thus, define 2 associations of edge vertex.

edge -- belongs_to --> :origin, class_name: 'vertex' edge -- belongs_to --> :terminus, class_name: 'vertex' 

i have restricted deletion of vertex part of edge. ensures cannot delete vertex part of graph, unless floating one.

but if try delete floating vertex (one part of graph not part of edge), still error:

activerecord::statementinvalid (mysql::error: unknown column 'edges.vertex_id' in 'where clause': select 1 one edges edges.vertex_id = ? limit 1)

now edges table obvious has no vertex_id, origin_id , terminus_id. how fix this?

i suggest specify foreign_key option:

specify foreign key used association. by default guessed name of association “_id” suffix. class defines belongs_to :person association use “person_id” default :foreign_key. similarly, belongs_to :favorite_person, class_name: "person" use foreign key of “favorite_person_id”.

belongs_to :origin, class_name: 'vertex', foreign_key: 'origin_id' belongs_to :terminus, class_name: 'vertex', foreign_key: 'terminus_id' 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -