Ruby on Rails | одна форма - три таблицы (невозможно сохранить содержимое формы) - PullRequest
0 голосов
/ 28 июня 2018

Я пытаюсь написать приложение - простую форму для сведений о пользователе, которая сохраняет данные в трех разных таблицах (1.users, 2.companies, 3.adresses). Я установил несколько ассоциаций, используя assign_to и has_many, а также использовал nested_attributes и fields_for для создания одной формы. Но я не могу сохранить данные. Я новичок, так что, вероятно, я делаю некоторые глупые ошибки, но я не могу найти их в течение 3 дней. Также пытался поискать в гугле и здесь, среди постов форума, но не нашел код, где проблема была связана с дочерним классом. Мои ассоциации между пользователем, компанией и адресом довольно странные. Может кто-нибудь мне помочь?

Вот моя форма:

<%= simple_form_for @user do |f| %>

    <h5>Personal Details</h5>
      <%= f.input :firstname, label: 'Your First Name:' %>
      <%= f.input :lastname, label: 'Your Last Name:' %>
      <%= f.input :email, label: 'Your Email:' %>
      <%= f.input :dateofbirth, label: 'Your Date of Birth:' %>
      <%= f.input :phonenumber, label: 'Your Phone Number' %>
    <h5>Adress</h5>

      <%= f.fields_for :adresses do |g| %>
          <%= g.input :street, label: 'Street:' %>
          <%= g.input :city, label: 'City:' %>
          <%= g.input :zipcode, label: 'Zip Code:' %>
          <%= g.input :country, label: 'Country:' %>
      <% end %>

     <h5>Company</h5>  
     <%= f.fields_for :companies do |h| %>
          <%= h.input :name, label: 'Name:' %>
     <% end %>      

     <%= f.fields_for :adresses do |i| %>
          <%= i.input :comstreet, label: 'Street:' %>  
          <%= i.input :comcity, label: 'City:' %>  
          <%= i.input :comzipcode, label: 'Zip Code:' %>  
          <%= i.input :comcountry, label: 'Country:' %>  
      <% end %>

      <%= f.button :submit %>
<% end %>

user.rb

class User < ApplicationRecord
  belongs_to :company, inverse_of: :users
  belongs_to :adress,  inverse_of: :users

  validates_presence_of :firstname, :lastname, :email
  validates_length_of :firstname, :maximum => 100
  validates_length_of :lastname, :maximum => 100
end

company.rb

class Company < ApplicationRecord
  has_many :users, inverse_of: :companies
  belongs_to :adress, inverse_of: :companies
  accepts_nested_attributes_for :users
end

adress.rb

class Adress < ApplicationRecord
  has_many :users, inverse_of: :adresses
  has_many :companies, inverse_of: :adresses

  accepts_nested_attributes_for :users, :companies
end

users_controller

class UsersController < ApplicationController

  def index
  end

  def new
   @user = User.new 
   @company = Company.new
   @adress = Adress.new
  end

  def create
    @user = User.new(user_params)
    if @user.save 
        redirect_to root_path
    end    
  end    

  private

  def user_params
    params.require(:user).permit(:firstname, :lastname, :email, :dateofbirth, 
    :phonenumber, company_attributes: [:name], 
    adress_attributes: [:street,:city, :zipcode, :country, :comstreet, 
    :comctiy, :comzipcode, :comcountry] )
  end    
end

Ответы [ 2 ]

0 голосов
/ 28 июня 2018

Я сделал несколько изменений в коде и смог сохранить форму, пожалуйста, отметьте

Вот моя форма:

<%= simple_form_for @user do |f| %>

    <h5>Personal Details</h5>
      <%= f.input :firstname, label: 'Your First Name:' %>
      <%= f.input :lastname, label: 'Your Last Name:' %>
      <%= f.input :email, label: 'Your Email:' %>
      <%= f.input :dateofbirth, label: 'Your Date of Birth:' %>
      <%= f.input :phonenumber, label: 'Your Phone Number' %>
    <h5>Adress</h5>

      <%= f.fields_for :adress_attributes do |g| %>
          <%= g.input :street, label: 'Street:' %>
          <%= g.input :city, label: 'City:' %>
          <%= g.input :zipcode, label: 'Zip Code:' %>
          <%= g.input :country, label: 'Country:' %>
      <% end %>

     <h5>Company</h5>  
     <%= f.fields_for :company_attributes do |h| %>
          <%= h.input :name, label: 'Name:' %>
            <%= h.fields_for :adress_attributes do |i| %>
              <%= i.input :street, label: 'Street:' %>  
              <%= i.input :city, label: 'City:' %>  
              <%= i.input :zipcode, label: 'Zip Code:' %>  
              <%= i.input :country, label: 'Country:' %>  
           <% end %>
     <% end %>      



      <%= f.button :submit %>
<% end %>

user.rb

class User < ApplicationRecord
  belongs_to :company, inverse_of: :users
  belongs_to :adress,  inverse_of: :users

  validates_presence_of :firstname, :lastname, :email
  validates_length_of :firstname, :maximum => 100
  validates_length_of :lastname, :maximum => 100
  accepts_nested_attributes_for :company
  accepts_nested_attributes_for :address
end

company.rb

class Company < ApplicationRecord
  has_many :users, inverse_of: :companies
  belongs_to :adress, inverse_of: :companies
  accepts_nested_attributes_for :users
  accepts_nested_attributes_for :adress
end

adress.rb

class Adress < ApplicationRecord
  has_many :users, inverse_of: :adresses
  has_many :companies, inverse_of: :adresses

  accepts_nested_attributes_for :users, :companies
end

users_controller

class UsersController < ApplicationController

  def index
  end

  def new
   @user = User.new 
  end

  def create
    @user = User.new(user_params)
    if @user.save 
        redirect_to root_path
    end    
  end    

  private

  def user_params
    params.require(:user).permit(:firstname, :lastname, :email, :dateofbirth, 
    :phonenumber, company_attributes: [:name, adress_attributes: [:street, 
    :ctiy, :zipcode, :country]], 
    adress_attributes: [:street,:city, :zipcode, :country] )
  end    
end

Он работает сейчас и может сохранить пользователя, адрес и компанию с адресом компании. enter image description here

0 голосов
/ 28 июня 2018

В вашем user.rb файле:

class User < ApplicationRecord
  belongs_to :company, inverse_of: :users
  belongs_to :adress,  inverse_of: :users

  validates_presence_of :firstname, :lastname, :email
  validates_length_of :firstname, :maximum => 100
  validates_length_of :lastname, :maximum => 100
  # add nested attributes here not in other models
  accepts_nested_attributes_for :companies
  accepts_nested_attributes_for :addresses

end

Также в вашем контроллере: внимательно проверяйте имена передаваемых параметров. address_attributes с ошибкой

def user_params
    params.require(:user).permit(:firstname, :lastname, :email, :dateofbirth, 
    :phonenumber, company_attributes: [:name], 
    address_attributes: [:street,:city, :zipcode, :country, :comstreet, 
    :comctiy, :comzipcode, :comcountry] )
  end 

В представлении удалите несколько элементов формы для адреса. Вы написали дважды.

...