Не удается обновить через ассоциацию: запись не найдена - PullRequest
0 голосов
/ 12 февраля 2019

Я не могу обновить настройки моей модели с Rails на Postgres DB.RecordNotFound in AccountsController#edit.

Я пытался вызывать форму разными способами без успеха.

Обновление 1: вызов формы был изменен на

                <% if current_user.accounts.first.present? %>
            <li class="list-group-item"><%= link_to "Account data",edit_account_path(@account, current_user) %></li>
            <% end %>

Обновление 2: изменение изменено на:

            <% if current_user.accounts.first.present? %>
            <li class="list-group-item"><%= link_to "Account data",edit_account_path(current_user.accounts.first) %></li>
            <% end %>

Модели:

class Account < ApplicationRecord
  # associations
  has_many :accounts_users
  has_many :users, :through => :accounts_users
  has_one :company 
end

class AccountsUser < ApplicationRecord
  # associations
  belongs_to :user
  belongs_to :account
end

class User < ApplicationRecord
  # associations 
 has_many :accounts_users
 has_many :accounts, :through => :accounts_users
 has_one :company, :through => :accounts_users 
end

Соответствующие действия контроллера учетной записи следующие:

 # POST /accounts
 # POST /accounts.json
 def create
 # create a new user if none exists
   if !current_user.present?
     build_resource(sign_in_params)
     account = Account.find_or_create_by(org_name: params[:user] [:account])
   else
# add the account for an existing user
     @account = current_user.accounts.new(account_params)
   end

# when a user account is create, add a company for that account
  # create a default account and company
     if resource.save
       resource.accounts << account
       if resource.current_account.companies.empty?
         company =   resource.current_account.companies.create({company_name: params[:user] [:account] })
       else
         company = resource.current_account.companies.first
       end
      resource.update(current_company: company.id)
 end

    respond_to do |format|
      if current_user.save
       format.html { redirect_to edit_account_url(@account), notice: 'Account was successfully created.' }
       format.json { render json: @account, status: :created, location: @account }
     else
       format.html { render action: "new" }
       format.json { render json: @account.errors, status: :unprocessable_entity }
     end
   end
 end

Действие редактирования и обновления:

  # GET /accounts/1/edit
   def edit
    @account = Account.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.js
      format.json { render json: @account }
    end
  end

 # PUT /accounts/1
 # PUT /accounts/1.json
 def update
    @account = Account.find(params[:id])

    respond_to do |format|
      if @account.update_attributes(account_params)
        format.html { redirect_to show_account_url(@account), notice: 'Your account has been updated successfully.'}
        format.json { head :no_content }
     else
       format.html { render action: "edit" }
        format.json { render json: @account.errors, status: :unprocessable_entity }
      end
   end
 end

, затем я вызываю форму с:

<% if current_user.accounts.first.present? %>
   <li class="list-group-item"><%= link_to "Account data",edit_account_path(current_user, @account) %></li>
 <% end %>

Маршруты следующие:

Rails.application.routes.draw do

  authenticated :user do
     root 'pages#home', as: :authenticated_root
  end
    root 'pages#index'

  devise_for :users,
          path: '',
          path_names: {sign_in: 'login', sign_out: 'logout', edit:  'profile', sign_up: 'registration'},
          controllers: {omniauth_callbacks: 'omniauth_callbacks',  registrations: 'registrations'}

resources :accounts
...
end

Я получаюследующая ошибка:

ActiveRecord::RecordNotFound in AccountsController#edit
Couldn't find Account with 'id'=2. 

, где id - это user id.

после обновления 1. Теперь ошибка:

    No route matches {:action=>"edit", :controller=>"accounts", :format=>#<User id: 2, email: "test@test.com", created_at: "2018-12-11 10:51:45", updated_at: "2019-02-11 22:34:57", fullname: "Jacques", provider: nil, uid: nil, image: nil, phone_number: nil, description: "", pin: nil, phone_verified: nil, stripe_id: "", unread: 1, merchant_id: nil, activation: 2, team_id: nil>, :id=>nil, :locale=>:fr}, possible unmatched constraints: [:id]

Япытается обновить учетную запись пользователя для правильного пользователя.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...