【发布时间】:2012-07-02 03:50:56
【问题描述】:
我到处寻找解决方案,但没有提出任何解决方案。
起作用的部分:我的应用程序允许客户使用嵌套表单创建帐户。收集的数据在四个模型中创建记录 - 帐户、用户、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)。
【问题讨论】:
-
我认为您没有在创建操作中将 current_account 与用户相关联。你可以试试@user = @current_account.users.new(params[:user]) 吗?
-
Alper - 我尝试了您的建议,但没有任何变化。除了您的建议之外,您是否认为我的代码看起来不错?或者,你还有其他想法吗?我正在把头发拉到这个上面!
-
我试过你的代码,它对我有用,创建新用户,除了它没有创建任何 AccountsUser。我按照我所说的修改了创建操作,并保存了 also @current_account。提交表单后可以提供一些日志吗?你的模型名称和关系看起来有点不同,我很难理解,但我看不出有什么问题。
-
@Alper - 我让它工作了。不确定这是否是正确的方法,所以如果您有任何其他建议,我会全力以赴。现在,当然,我面临其他问题(请参阅 Edit2 注释),但我会将它们保存为关于 SO 的另一个问题。
标签: ruby-on-rails nested-forms multi-tenant