Reputation: 486
My "child" form contains the following select:
<%= child.select :parent_id, options_for_select(Parent.all.map{ |parent| parent.grandparent.name + " - " + parent.name }, {:include_blank => true}) %>
On the "update" action, I get the following error:
Cannot add or update a child row: a foreign key constraint fails (`database_name`.`childs`, CONSTRAINT `fk_part2_5` FOREIGN KEY (`parent_id`) REFERENCES `parents` (`id`))
Models look like so:
class Child < ApplicationRecord
belongs_to :parent
end
class Parent < ApplicationRecord
has_many :childs, :dependent => :delete_all
end
class GrandParent < ApplicationRecord
has_many :parents, :dependent => :delete_all
end
Upvotes: 1
Views: 798
Reputation: 486
Figured it out. It was my select form that was wrong. The actual value of the individual select options was not the ID's, so it wasn't able to update the table. Figured it out as so:
<%= child.collection_select(:parent_id, Parent.all, :id, :parent_with_grandparent_name) %>
class Parent < ActiveRecord::Base
has_many :childs, :dependent => :delete_all
belongs_to :grandparent
def parent_with_grandparent_name
grandparent.name + " - " + name
end
end
Upvotes: 1
Reputation: 2791
In options_for_select call you use an array of option texts, which is incorrect. You need to use an array of pairs [option text, option value]:
<%= child.select :parent_id, options_for_select(Parent.all.map { |parent| ["#{parent.grandparent.name} - #{parent.name}", parent.id] }), { include_blank: true } %>
Upvotes: 0