我有 2 个模型,用户和患者。一个用户有一个病人,一个病人属于一个用户。
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
#
在我的患者 Controller 中,我正在尝试创建一个新的患者表单。
class PatientsController < ApplicationController
def new
@patient = Patient.new
end
end
在我看来 (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%>
表单显示为空白,带有提交按钮,没有为 user_fields 生成标记
我被告知我做错了,因为患者有 accepts_nested_attributes_for :user 并且它应该是用户嵌套属性但是在我的系统中我想使用资源模型以便患者和其他用户类型得到治疗分别。
示例数据库表:
用户:id|first_name|last_name...等
患者:id|user_id|保险
最佳答案
除非我弄错了,否则当您调用 fields_for
时,您没有 user
。在执行 fields_for
之前,您需要有一个可用于构建表单的用户实例,有点像您为您的 @patient
patient_form
.
你最好的选择是在你的 Controller 中基于你的 @patient
构建一个 User
,然后你就可以在 View 中访问它。
关于ruby-on-rails - 使用 accepts_nested_attributes_for 创建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5094008/