我有三个名为User
,Account
和AccountPermission
的模型。
我在User
和Account
到AccountPermission
之间建立了关联,因此,has_many :through
我还通过 creator_id 与User
建立了Account
和has_many
。因为,我需要知道帐户的创建者。
我使用嵌套属性创建Account
和User
同一时间。不过,我还想在同一笔交易中向我的User
添加 creator_id 。
你对这个案子有什么想法吗?
这是我的协会,
user.rb
class User < ActiveRecord::Base
has_many :created, class_name: 'Account', :foreign_key => 'creator_id'
has_many :account_permissions, :class_name => 'AccountPermission'
has_many :accounts, through: :account_permissions
accepts_nested_attributes_for :account_permissions
account.rb
class Account < ActiveRecord::Base
belongs_to :creator, class_name: 'User'
has_many :accounts_permissions, :class_name => 'AccountPermission'
has_many :users, through: :accounts_permissions
account_permission.rb
class AccountPermission < ApplicationRecord
belongs_to :user
belongs_to :account
accepts_nested_attributes_for :account
控制器#新
def new
@user = User.new
@user.account_permissions.build.build_account
respond_with(@user)
end
我的SQL,
(0.3ms) BEGIN
SQL (12.4ms) INSERT INTO "users" ("email", "encrypted_password", "first_name", "last_name", "created_at", "updated_at", "country") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["email", "testemail@gmail.com"], ["encrypted_password", "$2a$11$2XeCSewQ3JqIFNjwktfQZ.nt/.iWsT7ea6SSmVrrzWAcqHqMuubUy"], ["first_name", "test name"], ["last_name", "test lastname"], ["created_at", 2016-08-09 11:15:46 UTC], ["updated_at", 2016-08-09 11:15:46 UTC], ["country", "EC"]]
SQL (4.4ms) INSERT INTO "accounts" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["name", "testsubdomain"], ["created_at", 2016-08-09 11:15:46 UTC], ["updated_at", 2016-08-09 11:15:46 UTC]]
SQL (6.4ms) INSERT INTO "account_permissions" ("user_id", "account_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["user_id", 51], ["account_id", 19], ["created_at", 2016-08-09 11:15:46 UTC], ["updated_at", 2016-08-09 11:15:46 UTC]]
(1.9ms) COMMIT
(0.2ms) BEGIN