私はどこでも解決策を探しましたが、何も思いつきませんでした。
機能する部分: 私のアプリでは、顧客はネストされたフォームを使用してアカウントを作成できます。収集されたデータは、accounts、users、accounts_users (ユーザーは多くのアカウントに関連付けることができるため)、および profile (ユーザーの fname、lname、phone などを保存するため) の 4 つのモデルでレコードを作成します。
機能しない部分: ログインしたら、ユーザーが以下のフォームを使用して自分のアカウントにさらにユーザーを追加できるようにしたい. 送信時にエラーは発生しませんが、追加のレコードが作成されずに同じフォームに戻ります。どんな助けでも素晴らしいでしょう!
これがネストされたフォームです...
<%= 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 + password_comfirmation の検証が必要であったため、これらのフィールドがないと別のユーザーを追加できなかったことがわかりました。これらの検証をコメントアウトし、「new」アクションの current_account.accounts_users.build() 行を削除し、「create」アクションに @user.accounts_users.build(:account_id => current_account.id) 行を追加しました。