在另外两个模型之间创建关联时传递用户ID

时间:2016-03-01 20:27:10

标签: ruby-on-rails associations

我完全坚持看似应该如此简单的事情。我有一个订阅模型,可以创建与帐户模型的关联。这部分使用:

工作正常
after_create :create_account

我想要的是将用户传递到帐户记录中,理想情况下是帐户管理员。我也有一个user_id字段,但我更喜欢使用account_manager_id。我可以手动做到这一点,但让它自动发生就是绊倒我。我已经尝试了各种方法,通过在create下的帐户控制器中添加各种选项将当前用户传递到帐户。到目前为止没有运气。有没有人有任何想法?

@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

1 个答案:

答案 0 :(得分:0)

拿出

after_create :create_account

并添加以下内容

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