我可以使用 create 方法创建具有正确关联的记录,但如果我使用 build 然后保存实例,它不会创建关联。
这行得通
@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