我到处寻找解决方案,但没有提出任何解决方案。
起作用的部分:我的应用程序允许客户使用嵌套表单创建帐户。收集的数据在四个模型中创建记录 - 帐户、用户、accounts_users(因为一个用户可以与许多帐户相关联)和配置文件(用于存储用户的 fname、lname、电话等)。
那部分不起作用:登录后,我希望用户能够使用下面的表格将更多用户添加到他们的帐户中。我在提交时没有收到任何错误,但我被带回到同一个表单,没有创建额外的记录。任何帮助都是极好的!
这是嵌套形式...
<%= form_for @user, :validate => true do |f| %>
<fieldset>
<%= f.fields_for :profile do |p| %>
<div class="field">
<%= p.label :first_name %>
<%= p.text_field :first_name %>
</div>
<div class="field">
<%= p.label :last_name %>
<%= p.text_field :last_name %>
</div>
<div class="field">
<%= p.label :phone %>
<%= p.text_field :phone %>
</div>
<% end %>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit 'Create New User', :class => "btn btn-large btn-success" %>
<%= cancel %>
</div>
</fieldset>
ApplicationController 将所有内容都限定为 current_account,如下所示:
def current_account
@current_account ||= Account.find_by_subdomain(request.subdomain) if request.subdomain
end
用户控制器
def new
@user = User.new
@user.build_profile()
#current_account.accounts_users.build() #Edit2: This line was removed
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
def create
@user = User.new(params[:user])
@user.accounts_users.build(:account_id => current_account.id) #Edit2: This line was added
if @user.save
# Send Email and show 'success' message
flash[:success] = 'An email has been sent to the user'
else
# Render form again
render 'new'
end
end
模型如下所示:
class Account < ActiveRecord::Base
attr_accessible :name, :subdomain, :users_attributes
has_many :accounts_users
has_many :users, :through => :accounts_users
accepts_nested_attributes_for :users
end
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :profile_attributes
has_many :accounts_users
has_many :accounts, :through => :accounts_users
has_one :profile
accepts_nested_attributes_for :profile
end
class AccountsUser < ActiveRecord::Base
belongs_to :account
belongs_to :user
end
class Profile < ActiveRecord::Base
belongs_to :user
attr_accessible :first_name, :last_name, :phone
end
Edit2:事实证明,我需要在 User 模型中进行密码 + password_comfirmation 验证,这使我无法添加没有这些字段的其他用户。我注释掉了这些验证,并在“新”操作中删除了行:current_account.accounts_users.build(),并在“创建”操作中添加了行:@user.accounts_users.build(:account_id => current_account.id)。