Rails高级关联

时间:2016-08-09 11:19:55

标签: ruby-on-rails ruby

我有三个名为UserAccountAccountPermission的模型。

我在UserAccountAccountPermission之间建立了关联,因此,has_many :through

我还通过 creator_id User建立了Accounthas_many。因为,我需要知道帐户的创建者。

我使用嵌套属性创建AccountUser同一时间。不过,我还想在同一笔交易中向我的User添加 creator_id

你对这个案子有什么想法吗?

这是我的协会,

associations

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

0 个答案:

没有答案