每个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
病史方面看起来像下面
#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
什么的?
按如下方式更改模型:
class MedicalHistory < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
参考这里: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
您没有理由在#create
中使用类似 params[:medical_history]
的东西?
你可能想看看accepts_nested_attributes_for
有关介绍,请参阅此处http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes