I can create a record with the correct association using the create method, but if I use build then save the instance, It doesn’t create the association.
this works
@account = Account.find(params[:id])
@user = @account.users.create!(:profile_attributes => { name: name, company: company_name },email: email, password: password, password_confirmation: password)
but this will only create the user and not the association to the account, which is through a polymorphic membership model
@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
I want to use save so that I can use all the validations and callbacks on this.
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
module methods excluded
class Account < ActiveRecord::Base
include Membership::HasMembersMixin
end
Ah, now I realized. So, the thing is, when you create an AR instance, the associations which are not stored will be all saved. This is the default creation behaviour: save everything. But, if a record already exists, the changes on its associations made using it will not persist. Let’s say an account as a user, and this is an example:
So, this is default AR behaviour, there’s not much you can do. You can set :autosave => true on the association, but I wouldn’t recommend it (each time you would save an account, it would also always try to save all users, even though you hadn’t made any changes to them). It’s, let’s just say, a feature bug 🙂