leastbad / optimism

The missing drop-in solution for realtime remote form validation in Rails.
MIT License
361 stars 42 forks source link

Add belongs_to class errors to inferred foreign_key #38

Closed gathuku closed 3 years ago

gathuku commented 3 years ago

This PR proposes to add belongs_to class errors to the inferred foreign key method. This is useful when you need to display errors with rails collection select.

Examples

# app/models/post.rb
class Post < ApplicationRecord
  belongs_to :user
end
# post = Post.create 
# post.errors.messages # { user: ["Must must exist"] }
# app/views/post/_form.html.erb
<%= form.collection_select :user_id, User.all, :id, :name, {include_blank: true}, class: "field" %>
<%= form.error_for :user_id, class: "danger hide" %>
# app/controllers/post_controller.rb
params.require(:post).permit(:user_id)

Modified error object with proposed changes

# post.errors.messages # { user: ["Must must exist"] , user_id: ["Must must exist"]}
leastbad commented 3 years ago

Hey Moses, I'm super excited for this.

Right now I am trying hard to stay focused on StimulusReflex/CableReady documentation but this is next on my list!