使用Google Map与jt-rails-address为Rails用户添加地址遇问题求助
Hey there! Let's work through this issue you're facing with the jt-rails-address plugin and Google Maps autocomplete—since you're new to Rails, I'll break this down step by step to get you back on track.
1. Fixing the undefined local variable or method 'street' Error
This error almost always happens because your form isn't properly accessing the nested address properties that the jt-rails-address plugin sets up. When you add has_address :address to your User model, it creates database fields like address_street, address_city, etc., and gives you a nested address attribute to work with in forms.
Key checks to fix this:
- Verify your migration file: Double-check
add_address_to_users.rbto ensure it's creating fields prefixed withaddress_(e.g.,address_street,address_city,address_zipcode,address_country). If you initially created standalonestreet/cityfields, you'll need to adjust the migration, roll it back, and re-run it. - Update your form code: In
edit.html.erb, you must usefields_forto wrap your address input fields instead of calling them directly on the main form object. Here's how it should look:<%= form_with(model: @user) do |f| %> <!-- Your other user fields go here --> <%= f.fields_for :address do |address_fields| %> <%= address_fields.label :street %> <%= address_fields.text_field :street, id: 'autocomplete-street' %> <%= address_fields.label :city %> <%= address_fields.text_field :city %> <%= address_fields.label :zipcode %> <%= address_fields.text_field :zipcode %> <%= address_fields.label :country %> <%= address_fields.text_field :country %> <% end %> <%= f.submit "Save Changes" %> <% end %> - Fix strong parameters: Your
user_paramsmethod needs to explicitly permit the nested address attributes, not just the top-level:addresskey. Update it to:def user_params params.require(:user).permit( :name, :email, # Add your other user attributes here address: [:street, :city, :zipcode, :country] ) end
2. Fixing the "Cannot Input Address" Issue
Once you resolve the first error, if you still can't type or use autocomplete, the problem usually lies with Google Maps API setup or JavaScript initialization.
Key checks to fix this:
- Validate Google API permissions: Make sure your API key has both the Places API and Geocoding API enabled. If not, you'll see 403 errors in your browser's developer console (hit F12 to open it, then go to the Console tab).
- Adjust your JavaScript setup: Ensure you're loading the Google Maps Places library correctly and initializing autocomplete properly. If you're using Rails 7 with Turbo, use the
turbo:loadevent instead ofDOMContentLoadedto handle page refreshes. Here's a working example forapplication.js:// Load Google Maps Places API (replace YOUR_API_KEY with your actual key) import "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"; document.addEventListener('turbo:load', function() { const streetInput = document.getElementById('autocomplete-street'); if (!streetInput) return; // Initialize autocomplete const autocomplete = new google.maps.places.Autocomplete(streetInput, { types: ['address'] // Restrict results to actual addresses }); // Auto-fill other fields when a place is selected autocomplete.addListener('place_changed', function() { const place = autocomplete.getPlace(); place.address_components.forEach(component => { const types = component.types; if (types.includes('locality')) { document.querySelector('[name="user[address][city]"]').value = component.long_name; } if (types.includes('postal_code')) { document.querySelector('[name="user[address][zipcode]"]').value = component.long_name; } if (types.includes('country')) { document.querySelector('[name="user[address][country]"]').value = component.long_name; } }); }); }); - Check browser console for errors: Open your browser's developer console and look for errors like
google is not defined(means the Google Maps library didn't load) orCannot set property 'value' of null(means your field selectors are wrong). These errors will point directly to the root cause. - Confirm plugin setup: Double-check your User model to ensure
has_address :addressis spelled correctly and there are no typos.
Final Quick Checks
- Restart your Rails server to make sure all code changes take effect.
- Re-run your database migrations if you adjusted the migration file:
rails db:rollbackfollowed byrails db:migrate.
内容的提问来源于stack exchange,提问作者Benjamin Richard

