2012-02-19 76 views
1

当我的表单发布后,它将首先创建我的模型对象#1,如果成功,它将创建模型对象#2。我的表单是2个对象,我可以以某种方式嵌入2个对象吗?

我的表单字段需要混合使用两个模型对象的输入字段。

我可以使用表单助手来做到这一点,或者我应该手动执行此操作吗?

更新

下面是我的模型:

我的模型:

Account 
    has_many :users 
    has_one :primary_user, :class_name => 'User' 

User 
    has_one :account 

我的用户表有:

account_id 

我的帐户表:

primary_user_id 

所以登记/注册为帐户时,我想还包括从用户对象的字段:

user_name 
email 
password 

所以在创建帐户时,也创建了primary_user用户帐户。

我怎样才能做到这一点?

PSS:哪一边联想应该是空的,在user表中ACCOUNT_ID或账户上侧primary_user?因为目前我在双方都没有任何空位,所以无法工作!

+1

关联的对象?如果是这样,嵌套模型将照顾... ...仍然有一些工作,但形式助手仍然适合你。 – ScottJShea 2012-02-19 14:31:03

+0

没有它的嵌套,但实际上应该是。 – Blankman 2012-02-19 15:43:28

+0

该关系将是一个has_one关系。 – Blankman 2012-02-19 17:35:44

回答

1

型号代码

class Account < ActiveRecord::Base 
    has_many :users 
    has_one :primary_user, :class_name => "User", 
    :conditions => {:is_primary => true} 

    accepts_nested_attributes_for :primary_user, :allow_destroy => true 
end 

控制器代码

class AccountsController < ApplicationController 

    def new 
    @account = Account.new(:primary_user => User.new) 
    end 

    def create 
    @account = Account.new(params[:account]) 
    if @account.save 
     flash[:info] = "Created account" 
     redirect_to root_url 
    else 
     render :new 
    end 
    end 
end 

查看代码

- semantic_form_for @account do |f| 
    - f.inputs do 
    != f.input :company_name 
    != f.input :address 
    != f.input :city 
    != f.input :state 
    - f.semantic_fields_for :primary_user do |puf| 
     != f.input :name 
     != f.input :login 
     != f.input :password 
     != f.input :password_confirmation 
    - f.buttons do 
    != f.commit_button 'Save' 
    ! #{link_to 'Cancel', root_url} 
+0

如此调用账号保存会保存用户吗? – Blankman 2012-02-24 03:34:16

+0

是的,嵌套属性负责存储用户对象。 – 2012-02-24 08:28:31

相关问题