I use stone with embossed rails to use the shape object in my rails project.
I understand that the form object is probably overflowing for the sample code that I use below, but it is intended for demo purposes.
In the form I create user, and associated with this user post are two user_emails.
class User < ApplicationRecord
has_many :user_emails
end
class UserEmail < ApplicationRecord
belongs_to :user
end
Please note that I do not use accepts_nested_attributes_for :user_emailsin the model user. It seems to me that one of the main points of form objects is that it helps you avoid using it accepts_nested_attributes_for, so I'm trying to do it without it. I got this idea from this video , which talks about refactoring fat models. I have a link pointing to a video section on form objects, and it expresses how much he doesn't like it accepts_nested_attributes_for.
Then I will go on to create mine user_form:
class UserForm < Reform::Form
property :name
validates :name, presence: true
collection :user_emails do
property :email_text
validates :email_text, presence: true
end
end
So, the object user_formwraps the record user, and then a couple of records user_emailassociated with this record user. There userare level checks , but user_emailthis form is written to:
user#name should matter- everyone
user_email#email_textshould matter
: user, user_email. : .
, . : new create:
class UsersController < ApplicationController
def new
user = User.new
user.user_emails.build
user.user_emails.build
@user_form = UserForm.new(user)
end
def create
@user_form = UserForm.new(User.new(user_params))
if @user_form.valid?
@user_form.save
redirect_to users_path, notice: 'User was successfully created.'
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name, user_emails_attributes: [:_destroy, :id, :email_text])
end
end
: :
<h1>New User</h1>
<%= render 'form', user_form: @user_form %>
<%= link_to 'Back', users_path %>
# app/views/users/_form.html.erb
<%= form_for(user_form, url: users_path) do |f| %>
<% if user_form.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(user_form.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% user_form.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<% f.fields_for :user_emails do |email_form| %>
<div class="field">
<%= email_form.label :email_text %>
<%= email_form.text_field :email_text %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
: :

. , , . :
Parameters: {"utf8"=>"✓", "authenticity_token"=>"123abc==", "user"=>{"name"=>"neil", "user_emails_attributes"=>{"0"=>{"email_text"=>"email_test1"}, "1"=>{"email_text"=>""}}}, "commit"=>"Create User"}
ActiveModel::UnknownAttributeError (unknown attribute 'user_emails_attributes' for User.):
, .
? reform_rails accepts_nested_attributes? : , .
, -:
virtus gem, . .