2012-02-19 78 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

相關問題