CppNoob CppNoob - 1 year ago 101
Ruby Question

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

I am modeling a directed graph in a Rails application (Rails 4.2). Among the model objects are


can be part of many
- hence we have the following relationship:

vertex -- has_many --> edges

An edge is defined between two vertices - an origin and a terminus. Thus, we define two associations of the edge with a vertex.

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

I have also restricted the deletion of a vertex that is part of some edge. This ensures that I cannot delete a vertex which is part of the graph, unless it is a floating one.

But if I try to delete a floating vertex (one that is part of the graph but not part of any edge), I still get an error:

ActiveRecord::StatementInvalid (Mysql::Error: Unknown column 'edges.vertex_id' in 'where clause': SELECT 1 AS one FROM edges WHERE edges.vertex_id = ? LIMIT 1)

Now the edges table obvious has no vertex_id, only an
and a
. How do I fix this?

Answer Source

I suggest you to specify foreign_key option:

Specify the foreign key used for the association. By default this is guessed to be the name of the association with an “_id” suffix. So a class that defines a belongs_to :person association will use “person_id” as the default :foreign_key. Similarly, belongs_to :favorite_person, class_name: "Person" will use a 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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download