Creating a form with accepts_nested_attributes_for

I have 2 models, user and patient. User HAS_ONE Patient and patient BELONGS_TO user.

class Patient < ActiveRecord::Base
  belongs_to :user
  accepts_nested_attributes_for :user
  attr_accessible :user_id, :user_attributes
end

# == Schema Information
#
# Table name: patients
#
#  id         :integer         not null, primary key
#  user_id    :integer
#  insurance  :string(255)
#  created_at :datetime
#  updated_at :datetime
#



class User < ActiveRecord::Base
  has_one :patient

  attr_accessible :username, :password, :active, :disabled, :first_name, :last_name, 
  :address_1, :address_2, :city, :state, :postcode, :phone, :cell, :email
  attr_accessor :password
end


# == Schema Information
#
# Table name: users
#
#  id                 :integer         not null, primary key
#  username           :string(255)
#  encrypted_password :string(255)
#  salt               :string(255)
#  active             :boolean
#  disabled           :boolean
#  last_login         :time
#  first_name         :string(255)
#  last_name          :string(255)
#  address_1          :string(255)
#  address_2          :string(255)
#  city               :string(255)
#  state              :string(255)
#  postcode           :string(255)
#  phone              :string(255)
#  cell               :string(255)
#  email              :string(255)
#  created_at         :datetime
#  updated_at         :datetime
#

In my patient controller, I am trying to create a new patient form.

class PatientsController < ApplicationController
  def new
    @patient = Patient.new
  end
end

In My View (new.html.erb)

<%= form_for @patient do |patient_form| %>
<% patient_form.fields_for :user do |user_fields| %>
<table class="FormTable" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td class="label">
            <%= user_fields.label :username %> *:                       
        </td>
        <td class="input">
            <%= user_fields.text_field :username, :class=>"TextField" %>
        </td>
    </tr>
</table>
...
<%end%>
<%end%>

The form appears blank with a submit button without generated markup for user_fields

I was told that I am doing this wrong because the patient has an accepts_nested_attributes_for user: and he must be a user nested with attributes. BUT in my system I want to use the resource model to treat the patient and other types of users separately.

Example Database Table:

USERS: id | first_name | last_name ... etc.

PATIENTS: id | user_id | insurance

+3
source
3

, user, fields_for. fields_for, , , @patient patient_form.

user , @patient, .

+2

<%= patient_form.fields_for ? , , " ".

+1

thev , . 1.e, patient_form.fields_for <%= User , :

def new
  @patient = Patient.new
  @patient.user = User.new
end
0
source

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


All Articles