When my form gets posted, it will first create my model object#1, and if it succeeds, then it will create model object#2.
当我的表单被发布时,它将首先创建我的模型对象#1,如果它成功,那么它将创建模型对象#2。
My form field needs to have a mix of both input fields for both model objects.
我的表单字段需要混合两个模型对象的两个输入字段。
Can I do this using form helpers or should I just do this manually?
我可以使用表单助手来完成此操作,还是应该手动执行此操作?
Update
更新
Below are my models:
以下是我的模特:
My models:
我的模特:
Account
has_many :users
has_one :primary_user, :class_name => 'User'
User
has_one :account
My user table has:
我的用户表有:
account_id
My account table:
我的帐户表:
primary_user_id
So during registration/signup for an account, I want to also include the fields from the user object:
因此,在注册/注册帐户期间,我还想包含用户对象中的字段:
user_name
email
password
So when the account is created, the primary_user user account is also created.
因此,在创建帐户时,还会创建primary_user用户帐户。
How can I do this?
我怎样才能做到这一点?
PSS: Which side of the associate should be nullable, the account_id on the user table or the primary_user on the account side? Because currently I have no nulls on both sides and that won't work!
PSS:关联方的哪一方应该可以为空,用户表上的account_id或帐户方的primary_user?因为目前我双方都没有空,这是行不通的!
1 个解决方案
#1
1
Model code
型号代码
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
Controller Code
控制器代码
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
View code
查看代码
- 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}
#1
1
Model code
型号代码
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
Controller Code
控制器代码
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
View code
查看代码
- 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}