2016-03-01 2 views
-1

Я полностью застрял на чем-то, что кажется, должно быть так просто. У меня есть модель подписки, которая создает связь с моделью учетной записи. Эта часть работает отлично с помощью:Передайте идентификатор пользователя при создании связи между двумя другими моделями

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 
Смежные вопросы