Rails forms an object with embossed rails, and collections do not work or do not check

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.

# models/user.rb
class User < ApplicationRecord
  has_many :user_emails
end

# models/user_email.rb
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:

# app/forms/user_form.rb
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:

# app/controllers/users_controller.rb
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

: :

# app/views/users/_form.html.erb
<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 %>

: :

enter image description here

. , , . :

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, . .

+4
2

:

:

# app/models/user.rb
class User < ApplicationRecord
  has_many :user_emails
end

# app/models/user_email.rb
class UserEmail < ApplicationRecord
  belongs_to :user
end

# app/forms/user_form.rb
# if using the latest version of reform (2.2.4): you can now call validates on property 
class UserForm < Reform::Form
  property :name, validates: {presence: true}

  collection :user_emails do
    property :email_text, validates: {presence: true}
  end
end

:

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  before_action :user_form, only: [:new, :create]

  def new 
  end

  # validate method actually comes from reform this will persist your params to the Class objects
  # you added to the UserForm object. 
  # this will also return a boolean true or false based on if your UserForm is valid. 
  # you can pass either params[:user][:user_emails] or params[:user][user_email_attributes]. 
  # Reform is smart enough to pick up on both.
  # I'm not sure you need to use strong parameters but you can. 

  def create    
    if @user_form.validate(user_params)
      @user_form.save
      redirect_to users_path, notice: 'User was successfully created.'
    else
      render :new
    end
  end

  private

  # call this method in a hook so you don't have to repeat
  def user_form
    user = User.new(user_emails: [UserEmail.new, UserEmail.new])
    @user_form ||= UserForm.new(user)
  end 

  # no need to add :id in user_emails_attributes
  def user_params
    params.require(:user).permit(:name, user_emails_attributes: [:_destroy, :email_text])
   end
 end

:

# app/views/users/new.html.erb
<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 %>
+5

- !!!

-, Rails 5. 4.2.6, . github Reform.

, :

/user.rb

class User < ActiveRecord::Base
  has_many :user_emails
end

/user_email.rb

class UserEmail < ActiveRecord::Base
  belongs_to :user
end

user_form.rb

class UserForm < Reform::Form

  property :name
  validates :name, presence: true

  collection :user_emails, populate_if_empty: UserEmail do
    property :email_text
    validates :email_text, presence: true
  end
end

populate_if_empty .

:

def create
  @user_form = UserForm.new(User.new)
  if @user_form.validate(user_params)
    @user_form.save
    redirect_to users_path, notice: 'User was successfully created.'
  else
    render :new
  end
end

AS WELL AS .

! , .

, !

+1

Source: https://habr.com/ru/post/1672581/


All Articles