每个User
只能有一个MedicalHistory
所以我有
class User < ActiveRecord::Base
acts_as_authentic
end
class MedicalHistory < ActiveRecord::Base
belongs_to :user
end
使用上面的内容,我可以在控制台的MedicalHistory
模型中成功创建用户:
newuser = Medicalhistory.new
newuser.user = User.new
newuser.user.username='testusername'
newuser.user.password='blahblah'
newuser.user.password_confirmation='blahblah'
newuser.user.save
MedicalHistory Side看起来像是
#controller
def new
@medicalhistory = MedicalHistory.new
@medicalhistory.user = User.new
end
#form
<%=...%>
<%=f.intput :cell_phone%>
<%=f.fields_for :user do |builder|%>
<%= render "registration_form", :f => builder %>
<% end %>
#Partial
<%=f.input :email%>
<%=f.input :password%>
<%=f.input :password_confirmation%>
错误
提交表单时,我收到以下错误:
User(#-) expected, got ActiveSupport::HashWithIndifferentAccess(#)
错误在以下行:
#controller
def create
@medicalhistory = Medicalhistory.new(session[:medicalhistory_params]) #gives error
#somewhere here I should extract registration fields and register the user
end
问题
有没有办法可以避免部分(注册字段)中的字段进入session[:medicalhistory_params]
...是否有except
或其他内容?
答案 0 :(得分:1)
按如下方式更改模型:
class MedicalHistory < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
参考此处:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
答案 1 :(得分:0)
是否有理由不在params[:medical_history]
中使用#create
之类的内容?
答案 2 :(得分:0)
您可能需要查看accepts_nested_attributes_for
请参阅此内容 http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes