以多模型forms链接两个模型

我现在有一个嵌套的多模型表单,使用用户和配置文件。

用户has_one配置文件,配置文件belongs_to用户。

提交表单时,会创建一个新用户,并创建一个新的配置文件,但它们没有链接(这是第一个明显的问题)。 用户的模型具有profile_id行,而配置文件的模型具有user_id行。

以下是表单的代码:

 teams_path) do |f| %> 




@role.id %>

current_user.company_id %>



第二个问题是,即使通过用户模型的表单成功创建了用户名和密码,也不会创建隐藏字段(role_id和company_id – 也是其他模型的链接)(即使它们是model) – 然而,这些值在HTML中成功显示。

任何帮助都会很棒!

根据要求,控制器代码:

  def new @user = User.new @user.profile = Profile.new @role = Role.find_by_name("Regular") respond_to do |format| format.html # index.html.erb format.xml { render :xml => @teams } end end def create @user = User.new(params[:user]) @profile = Profile.new(params[:profile]) respond_to do |format| if @profile.save && @user.save format.html { redirect_to (teams_path) } format.xml { render :xml => @profile, :status => :created, :location => @profile } else format.html { render :action => "new" } format.xml { render :xml => @profile.errors, :status => :unprocessable_entity } end end end 

要回答第一个问题,请更改以下内容:

 @profile = Profile.new(params[:profile]) 

 @profile = @user.profile.build(params[:profile]) #In the case of a has_many relationship 

要么

 @profile = @user.build_profile(params[:profile]) #In the case of a has_one relationship 

build命令构建一个新的配置文件,并正确设置user_id。

对于第二个问题,您是否可以在新操作期间删除角色和公司的查询,而是在创建操作期间分配这些查询? 这将消除传递隐藏参数的必要性。