Rails 3 중첩 된 자원 변수
-
15-11-2019 - |
문제
제가 생성하는 트랜잭션 객체와 관련된 몇 가지 질문이 있습니다.
트랜잭션은 융자 및 대출 has_many 거래를 거래합니다.
다음에 중첩 된 경로를 설정합니다.
resources :loans do
resources :transactions
end
.
내 질문은 다음과 같습니다. 대출 값을 트랜잭션의 'loan_id'필드에 어떻게 전달합니까?이것은 컨트롤러에서 또는 양식에서 HIDDEN_FIELD로 가장 잘 수행됩니까?중첩 된 경로 가이 변수를 잡는 쉬운 방법을 만들 수 있습니까?
이 작업이 자동으로 수행 될 것이라고 가정했지만 다음과 같이 저장할 때 필드가 비어 있습니다.
도움이 크게 감사 할 것입니다!
해결책
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
다른 팁
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