2016-03-01 30 views
-1

之間的關聯時,我完全被卡住的東西,似乎應該是這麼簡單。我有一個訂閱模式,可以創建與帳戶模型的關聯。這部分工作正常使用:通行證用戶ID創建其他兩款車型

after_create :create_account 

我想要的是將用戶傳遞到帳戶記錄,理想情況下作爲account_manager。我也有一個user_id字段,但我更喜歡使用account_manager_id。我可以手動做到這一點,但讓它自動發生讓我絆倒。我嘗試了多種方法,通過在創建帳戶控制器中添加各種選項,將當前用戶傳入帳戶。到目前爲止沒有運氣。有沒有人有任何想法?

@account = Account.new(params[:account].merge(account_manager_id: current_owner)) 


@user = current_user 
@account = @user.accounts.create(params[:account]) 


@account = Account.new(account_params) 
@account.account_manager = current_user 


@account = current_user.accounts.build(params[:account]) 

我的帳戶控制器

class AccountsController < ApplicationController 

    def index 
    @accounts = Account.all 
    end 

    def show 
    @account = Account.find(params[:id]) 
    end 

    def new 
    @account = Account.new 
    end 

    def edit 
    @account = Account.find(params[:id]) 
    end 

    def create 
    @account = Account.new(account_params) 
    @account.account_manager = current_user 
     if @account.save 
     flash[:success] = "Content Successfully Created" 
     redirect_to @account 
     else 
     render 'new' 
    end 
    end 

    def update 
    @account = Account.find(params[:id]) 
     if @account.update(account_params) 
     flash[:success] = "Your account was successfully updated" 
     redirect_to current_user 
     else 
     render 'edit' 
    end 
    end 

    def destroy 
    @account = Account.find(params[:id]) 
    @account.destroy 
    respond_to do |format| 
     flash[:info] = "The grant was successfully destroyed" 
    end 
    end 

    private 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def account_params 
     params.require(:account).permit(:name, :user_id, :account_manager_id,:subscription_id) 
    end 
end 

account.rb

class Account < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    belongs_to :account_manager, :class_name => 'User', :foreign_key => 'account_manager_id' 
    belongs_to :subscription, :dependent => :destroy 
end 

user.rb

class User < ActiveRecord::Base 
    has_one :subscription 
    has_and_belongs_to_many :account 

subscription.rb

class Subscription < ActiveRecord::Base 
    include Koudoku::Subscription 

    has_one :account 
    belongs_to :user 
    belongs_to :coupon 
    after_create :create_account #after a subscription is created, automatically create an associtaed account 

end 
+0

提供的車型代碼和控制器進行審查。 – Dharam

+0

您是否收到錯誤?如果是這樣,請發帖。此外,你在幾個地方拼寫「經理」錯誤(「經理」)。 – jvillian

+0

啊,很好的抓住了「經理人」。我在創建訂閱時沒有在網站上發現任何錯誤。但是當我檢查Account.all account_manager_id和user_id都是零。 – railsie

回答

0

掏出

after_create :create_account 

,並增加了以下

# subscriptions_controller.rb 
def create 
    ... 
    if @subscription.save 
    @subscription.create_account(account_manager: current_user) 
    end 
end