Using scaffold, I generated two models, Person and Offer, and the forms to manage them. Offer has a belong_to association with Person. After running the generator, all the forms immediately worked fine.
But then I discovered an external requirement that the foreign key column in the offers table, which was named person_id per Rails conventions, needed to be renamed as worker_id. Since then, the Offer forms don’t work. They evoke a variety of errors, all related to the renamed column. It seems that the system no longer recognizes it as implementing the Offer to Person association.
I figure I need to make some declaration somewhere to restore this associative functionality, but I can’t figure out how to do this. Can you help?
Here are some details:
The generate commands I used were:
rails generate scaffold Person name:string
rails generate scaffold Offer terms:string person:belongs_to rake db:migrate
<% @offers.each do |offer| %>
<% end %>
I tweaked the Offer forms a bit to show People’s names in display pages and provide a drop-down on edit forms. The tweaked Offer index.html.erb looked like this:
``and the tweaked Offer _form.html.erb looked like this:
<%= form_with(model: offer, local: true) do |form| %>
At this point, everything worked fine.
Then I wrote and executed this migration:
class RenameOfferPersonId < ActiveRecord::Migration[5.1]
rename_column :offers :person_id :worker_id
Since then, all of my Offer forms get errors, always related to the renamed foreign key column. Here’s the error for index.html.erb:
Showing /home/ec2-user/environment/ww1/app/views/offers/index.html.erb where line #18 raised:
undefined method `name' for nil:NilClass ... <td><%= offer.person.name %></td>
If I change the offending line to:
the page displays, but only the value of worker_id is displayed, not the name of the referenced Person.
The Offer edit form displays, including its dropdown box containing Person names. But when I try to save an update, I get:
ActiveModel::UnknownAttributeError in OffersController#update
unknown attribute ‘person_id’ for Offer.
Extracted source (around line #44):
44 if @offer.update(offer_params) `` If I change these lines in _form.html.erb ` <%= form.label :person_id %> <%= form.collection_select :person_id, Person.order(:name), :id, :name %> ` `` to ` <%= form.label :worker_id %> <%= form.collection_select :worker_id, Person.order(:name), :id, :name %> ` `` the form still displays OK, but when I try to save an update, I get a different error: 1 error prohibited this offer from being saved: - Person must exist `` ~ Thanks in advance for your help ~ Ken