我已到處搜索解決方案,但尚未提出任何解決方案。多模式嵌套表單,無法將用戶添加到當前帳戶
工作部分:我的應用程序允許客戶使用嵌套窗體創建帳戶。收集到的數據以四種模式創建記錄 - 帳戶,用戶,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
的UsersController
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
編輯2:事實證明,我在用戶模型中需要密碼+ password_comfirmation驗證,以防止我添加沒有這些字段的其他用戶。我註釋了這些驗證,並在'new'操作中刪除了以下行:current_account.accounts_users.build(),並在'create'操作中添加了以下行:@ user.accounts_users.build(:account_id => current_account.id)。
我想你不是在創建操作中將current_account與用戶關聯起來。你可以嘗試@user = @ current_account.users.new(params [:user])? –
Alper - 我嘗試了你的建議,但沒有改變。你是否認爲我的代碼看起來不錯,除了你的建議?或者,你有其他想法嗎?我正在把頭髮拉出這個! – hugo
我試過你的代碼,它爲我工作,創建新用戶,除非它不創建任何AccountsUser。我修改了創建操作,並保存了_also_ @ current_account。您可以在提交表單後提供一些日誌嗎?你的模型名稱和關係看起來有點不同,很難理解,但我看不出有什麼不對。 –