Как очистить код и устранить исключение NoMethodError - PullRequest
0 голосов
/ 03 октября 2019

Когда пользователь создает учетные записи, код должен позволять этому пользователю зарегистрировать учетную запись пользователя через Devise, а затем создать учетную запись, а также компанию.

Код должен быть перенаправлен в настройки мастера с использованием wicked. драгоценный камень. Пользователи имеют роли (rolify) и авторизуются с помощью Cancancan.

Таблицы настраиваются с использованием has_many: through сопоставления. Кажется, это работает.

Модели следующие:

user
   has_many :accounts_users
   has_many :accounts, through: :accounts_users, dependent: :destroy
   has_one :company, through: :accounts, dependent: :destroy


users_account
    belongs_to :account
    belongs_to :user

account
    resourcify
    has_many :accounts_users
    has_many :users, through: :accounts_users, dependent: :destroy
    has_one :company

company
    belongs_to :account

Контроллер создания учетной записи выглядит следующим образом:

  def new
    @account = Account.new
  end

def create
    if !current_user.present?
      build_resource(sign_in_params)
      account = Account.find_or_create_by(org_name: params[:user]    [:account])
    else
      @account = current_user.accounts.create!(account_params)
    end

# create a default account and company
    @account.save!
    current_user.add_role 'owner'
    current_account = current_user.accounts.first
# create a company associated with the newly created account
    if current_account.companies.empty?
      company = current_account.companies.create(company_name: params[:org_name])
    else
      company = current_account.companies.first
    end
    resource.update(current_company: company.id)
    respond_to do |format|
      if @account.save
 # redirect to the relevant wizard
        format.html { redirect_to after_account_path(:add_account),     notice: 'Account was successfully created.' }
      else
        format.html { render action: 'new' }
        format.json { render json: @account.errors, status: :unprocessable_entity }
      end
    end
  end

РЕДАКТИРОВАННАЯ ВЕРСИЯ

  def create
    @account = Account.create(account_params.except(:company))
    @account.save!
    respond_to do |format|
      if @account.save
        create_company
        format.html { redirect_to @account, notice: 'Account was successfully created.' }
        format.json { render :show, status: :created, location: @account }
      else
        format.html { render :new }
        format.json { render json: @account.errors, status: :unprocessable_entity }
      end
    end
  end

  def create_company
    current_user.add_role 'owner'
    current_account = current_user.accounts.first
    if current_account.company.nil?
      current_account.build_company(company_name: params[:org_name])
      @company.save!
    else
      company = current_account.company
    end
    resource.update(current_company: company.id)
  end

, включенный в помощник по приложениям:

  def current_account
    current_user.accounts.first
  end

  def current_company
    current_user.accounts.first.companies.first
  end

он перенаправляет (неожиданно) на отображение (показ) данных компании сразу после создания, я получаю сообщение об ошибке nil / no.

Индекс и как контроллер:

before_action :set_company, only: [:show, :edit, :update, :destroy,

: новый]

  def index; end

  def show
    @company = Company.find_by(id: params[:id])
  end


  def set_company
    @company = current_account.company
  end 

Это похоже на работу. Редактирование компании - это сложная задача, но она должна быть решена.

Любые советы по улучшению кода приветствуются

1 Ответ

0 голосов
/ 04 октября 2019

Вы когда-нибудь задумывались над тем, чтобы сделать переднюю ручку так, чтобы #name еще не было установлено?

<=% @company&.name %>

или

<=% @company.name || "Unknown" %>
...