create メソッドを使用して正しい関連付けでレコードを作成できますが、ビルドを使用してからインスタンスを保存すると、関連付けが作成されません。
これは動作します
@account = Account.find(params[:id])
@user = @account.users.create!(:profile_attributes => { name: name, company: company_name },email: email, password: password, password_confirmation: password)
ただし、これはユーザーを作成するだけで、アカウントへの関連付けは作成しません。これは、ポリモーフィック メンバーシップ モデルによるものです。
@account = Account.find(params[:id])
@user = account.users.build(:profile_attributes => { name: name, company: company_name },email: email, password: password, password_confirmation: password)
@user.save
これですべての検証とコールバックを使用できるように、save を使用したいと考えています。
メンバーシップ.rb
class Membership < ActiveRecord::Base
belongs_to :target, polymorphic: true
belongs_to :user
belongs_to :team
validates :target, presence: true
validate :has_user_or_team
module HasMembersMixin
extend ActiveSupport::Concern
included do
has_many :memberships, as: :target
has_many :users, through: :memberships
end
module ClassMethods
def accessible_by(user)
conditions = Membership.arel_for_user_or_their_teams(user)
if direct_conditions = directly_accessible_by(user)
conditions = conditions.or(direct_conditions)
end
includes(:memberships).where conditions
end
end
end
モジュールメソッドが除外されました
class Account < ActiveRecord::Base
include Membership::HasMembersMixin
end