1

I have a few questions relating to a Transaction object that I'm creating.

Transaction belongs_to Loan and Loan has_many Transactions.

Therefore, I setup a nested route:

resources :loans do
  resources :transactions
end

My question is: How do I pass the loan value into the Transaction's 'loan_id' field? Is this best done in the controller or as a hidden_field in the form? Does the nested route create an easy way to grab this variable?

I assumed this would be done automatically, but the field is empty when I saved it as-is.

Any help would be greatly appreciated!

2 Answers 2

2

if you call a specific transaction, the route for a new transaction will be

loans/:loan_id/transactions/new

you could use model association like this: in your create action:

@transaction = Loan.find(params[:loan_id]).transactions.build

that way your new @transaction will be already populated with the loan_id

Sign up to request clarification or add additional context in comments.

7 Comments

I just tried this and I got the following message: Couldn't find Loan without an ID. Do you why the :loan_id isn't being recognized?
make sure you have a loan in the database with the :loan_id you're trying to call. calling find on Loan will raise an exception if the loan with the id = loan_id does not exist - that should only happen if you type the url manually
The Loan exists and I'm linking to it with <%= link_to 'Lend Now', new_loan_transaction_path(@loan), :class => 'lend_button' %> Is that correct? It's still throwing the error for some reason. Thanks for the added help!
the link is correct (the action new, for a transaction in @loan). when is the error thrown? in the new or create action? what prints if you puts params[:loan_id]? is it the id of the called loan?
The error is thrown right after submitting the new Transaction form and it's titled ActiveRecord::RecordNotFound in TransactionsController#create. So, it's in the create method. There appears to be nothing in the params[:loan_id]. For some reason, I don't think the two are connecting. Is there something I need to add beyond what I have above to the routes perhaps? Thanks again, I really appreciate the help!
|
0

Consider adding a before_filter to your controller and having it call a private method to grab the :id across all actions. Place this at the top of your transactions controller:

before_filter :load_loan

And then after all the actions, add:

private
def load_loan
  @loan.find(params[:loan_id])
end

Use it like this in your new action:

@transaction = @loan.transactions.build

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.