0

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
4

2 に答える 2

0

少なくとも、アカウント モデルでこれを宣言する必要があると思います: accepts_nested_attributes_for :profile. accept_nested_attributes_for の API

ところで、モジュールを lib ファイルではなくモデル内で宣言したのはなぜですか?

于 2012-10-27T11:51:18.067 に答える
0

あ、今気づきました。つまり、AR インスタンスを作成すると、保存されていない関連付けはすべて保存されます。これはデフォルトの作成動作です: すべてを保存します。ただし、レコードが既に存在する場合、それを使用して行われた関連付けの変更は保持されません。アカウントをユーザーとして考えてみましょう。これは例です。

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 => true を設定できますが、お勧めしません (アカウントを保存するたびに、変更を加えていなくても、常にすべてのユーザーを保存しようとします)。 . それは、機能のバグです:)

于 2012-10-28T22:59:11.893 に答える