我可以使用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,以便我可以使用所有验证和回调。
membership.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
答案 0 :(得分:0)
我认为至少您应该在帐户模型中声明这一点:accepts_nested_attributes_for :profile
。 Api for accepts_nested_attributes_for
顺便说一下,为什么在模型中而不是在lib文件中声明模块?
答案 1 :(得分:0)
Account.new(:user => User.new) # this saves the account and the user
a = Account.find(params[:id]); a.user.name = "Boris Karloff" ; a.save # this will not store the user name
所以,这是默认的AR行为,你可以做的并不多。您可以设置:autosave =&gt;在关联上是真的,但我不推荐它(每次你保存一个帐户,它也总是会尝试保存所有用户,即使你没有对它们做任何更改)。我们只是说,这是一个功能错误:)