Whenever I try to save or update my AppTransaction model, it doesn’t let me. It was working before I added the account system, and then it started giving me an error about there not being a user_id method for app_transactions. Do you guys know why?
Error
undefined method `user_id’ for an instance of AppTransaction
Extracted source (around line #34):
`
@transaction = @account.app_transactions.build(transaction_params)
if @transaction.save <- this is line 34
redirect_to account_app_transactions_path @account
else
render :new, status: :unprocessable_entity`
AppTransactions#create
def create
@user = User.find(session[:user_id])
@account = @user.accounts.find(params[:account_id])
@transaction = @account.app_transactions.build(transaction_params)
if @transaction.save
redirect_to account_app_transactions_path @account
else
render :new, status: :unprocessable_entity
end
end
transaction_params
def transaction_params
params.expect(app_transaction: [ :amount, :category, :date, :summary, :details, :is_income ])
end
user.rb
class User < ApplicationRecord
has_many :accounts, dependent: :destroy
has_many :categories, dependent: :destroy
end
account.rb
class Account < ApplicationRecord
belongs_to :user
has_many :app_transactions, dependent: :destroy
end
app_transaction.rb
class AppTransaction < ApplicationRecord
belongs_to :account
end
Columns for AppTransaction
AppTransaction(id: integer, amount: float, category: string, date: datetime, account_id: integer, created_at: datetime, updated_at: datetime, summary: string, details: text, is_income: boolean)
I’ve tried replacing .save with .save!, doing @user.accounts.find() vs. Accounts.find(), and messing with the app_transaction.rb file, but I still get the same error every time.
4
The problem with the question is that it doesn’t give full information to see where the issue is
I would double-check that Accounts
has a user_id column(foreign key) in the database.
Or the Migration of Accounts table should be
On table creation, it should have
t.belongs_to :user
or
t.references :user
This will create a user_id column in the accounts
To test you can create Accounts using the rails console.
rails c
Account.create!(...require_fields)
Silas Getachew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.