Creating Form with accepts_nested_attributes_for
I have 2 models, a User and Patient. A User HAS_ONE Patient and a Patient BELONGS_TO a User.
class Patient < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
attr_accessible :user_id, :user_attribu开发者_如何学运维tes
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 patients 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 shows up blank with a submit button with no generated markup for the user_fields
I have been told I am doing this wrong because of the patient having the accepts_nested_attributes_for :user and it should be the user nesting the attributes BUT in my system I want to use the resources model so a patient and other user types are treated separately.
Example Database table:
USERS: id|first_name|last_name...etc
PATIENTS: id|user_id|insurance
Unless I'm mistaken, you have no user
when you are calling fields_for
. Before you can do the fields_for
, you will need to have an instance of a user that can be used to build the form, kind of like how you have @patient
for your patient_form
.
Your best bet would be to build a User
in your controller, based off of your @patient
, and then you will have access to that in the view.
try <%= patient_form.fields_for
with the equals sign in there? I know there was a warning message for awhile about "block style helpers are deprecated".
The answers from Jeff Casimir and theIV are correct, but you need to do them both. I.e., fix the patient_form.fields_for
block to user <%=
, and build a User object for the Patient in the controller, something like:
def new
@patient = Patient.new
@patient.user = User.new
end
精彩评论